diff --git "a/3036.jsonl" "b/3036.jsonl" new file mode 100644--- /dev/null +++ "b/3036.jsonl" @@ -0,0 +1,1924 @@ +{"seq_id":"1879628952","text":"from flask import Flask, request, redirect, url_for, flash, jsonify\nimport numpy as np\nimport pickle as p\nimport json\n\nfrom interface import chat\n\napp = Flask(__name__)\n\n@app.route('/api/', methods=['GET','POST'])\ndef chatBot():\n global chatInput\n if request.method == 'POST':\n chatInput = (request.get_json(force=True))\n print(chatInput)\n global chatBotReply\n chatBotReply = chat(chatInput)\n return jsonify(chatBotReply)\n\nif __name__ == '__main__':\n app.run(debug=True, host='192.168.1.6', port='5000')\n modelfile = 'tokenizer.pickle'\n model = p.load(open(modelfile, 'rb'))","repo_name":"zahwaaa/b21-cap0178-lapokap","sub_path":"Model/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3112633591","text":"# Apply math module\r\nimport math\r\n\r\n# Request the user to choose either investment or bond they want to do and store the selection into variable called calculation\r\n# The menu introduce the difference of two calculations\r\ncalculation=str(input('''Choose either \\'investment\\' or \\'bond\\' from the menu below to proceed: \\n\r\ninvestment \\t -\\tto calculate the amount of interest you'll earn on your investment\r\nbond \\t\\t - \\tto calculate the amount you'll have to pay on a home loan \\n'''))\r\n\r\n# Standardise the selection input into a recognised valid input by changing all characters into lower letter\r\ncalculation=calculation.lower()\r\n\r\n''' Display \"Thank you for using our service!\" if the user input correct selection\r\n Display \"Sorry. Please make sure you select 'investment' or 'bond'.\" if the user does not type in a valid input\r\n'''\r\nif calculation == \"investment\" or calculation==\"bond\":\r\n print(\"\\n \\tThank you for using our service!\\n\")\r\nelse:\r\n print(\"Sorry. Please make sure you select \\'investment\\' or \\'bond\\'.\")\r\n\r\n''' If the user choose 'investment', request the user to input the amount of money the user is depositing and store in a variable called amount.\r\n Request the user to input the interest rate and store in a variable called rate.\r\n Request the user to input the number of years they plan on investing and store in a variable called years.\r\n Request the user to input type of interest plan between 'Simple' and 'Compound' and store in a variable called interest.\r\n Standardise the interest plan selection input into a recognised valid input by changing all characters into lower letter\r\n Calculate the interest rate from percentage to decimal place form by dividing it by 100\r\n\r\n After that, to check the user has valid input or not.\r\n Display \"Thank you for your investment!\" if the user input correct selection\r\n Display \"Sorry. You have not selected 'simple' or 'compound'.\" if the user does not type in a valid input\r\n \r\n If the user selected 'simple' interest plan, calculate the total amount of money by specific equation.\r\n Display the result to the user\r\n If the user selected 'compound' inerest plan, calculate the total amount of money by specific equation.\r\n Display the result to the user\r\n If the user did not input a valid selection, display \"Please try again and make sure you select 'simple' or 'compound'.\"\r\n'''\r\nif calculation == \"investment\":\r\n amount=float(input(\"Please enter the amount of money you are depositing: \"))\r\n rate=float(input(\"Please enter the interest rate (as a percentage so you do not need to enter %) : \"))\r\n years=int(input(\"Please enter the years of plan on investing: \"))\r\n interest=str(input(\"Please choose \\'simple\\' or \\'compound\\' interest plan: \"))\r\n interest=interest.lower()\r\n rate=rate/100\r\n\r\n if interest == \"simple\" or interest==\"compound\":\r\n print(\"\\n \\tThank you for your investment!\\n\")\r\n else:\r\n print(\"\\n \\tSorry. You have not selected \\'simple\\' or \\'compound\\'.\\n\")\r\n \r\n if interest== \"simple\":\r\n total=amount*(1+rate*years)\r\n print(f\"The total amount once {interest} interest has been applied is: {total}\")\r\n elif interest== \"compound\":\r\n total=round(amount*math.pow((1+rate),years),2)\r\n print(f\"The total amount once {interest} interest has been applied is: {total}\")\r\n else:\r\n print(\"Please try again and make sure you select \\'simple\\' or \\'compound\\'.\")\r\n\r\n''' If the user choose 'Bond', request the present value of user's house and store into a variable called house_value.\r\n Request the annual interest rate and store into a variable called rate.\r\n Request the number of months the user plan to repay the bond and store into a variable called months.\r\n After that calculate the monthly interest rate by dividing annual interest rate by 12.\r\n Calculate the monthly repayment by specific equation\r\n Display the monthly repayment\r\n'''\r\n\r\nif calculation==\"bond\":\r\n house_value=float(input(\"Please enter the present value of your house: \"))\r\n rate=float(input(\"Please enter the interest rate (as a percentage so you do not need to enter %) : \"))\r\n months=int(input(\"Please enter the number of months you plan to repay the bond: \"))\r\n\r\n rate=rate/100/12\r\n repay=round((rate*house_value)/(1-math.pow((1+rate),-months)),2)\r\n print(f\"\\nYou will have to repay {repay} each month.\")\r\n ","repo_name":"scleungw/finalCapstone","sub_path":"finance_calculators.py","file_name":"finance_calculators.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"40832103941","text":"import sys\nfrom collections import deque\n\n\ndef main():\n test_case = int(input())\n\n for case_count in range(test_case):\n function_command = sys.stdin.readline().rstrip()\n numbers_count = int(sys.stdin.readline())\n queue = deque(sys.stdin.readline().rstrip()[1:-1].split(\",\"))\n if numbers_count == 0:\n queue = deque()\n\n result_queue = calculate(function_command, queue, numbers_count)\n\n if result_queue == \"error\":\n print(result_queue)\n else:\n print(\"[\" + \",\".join(result_queue) + \"]\")\n\n\ndef calculate(function_command, queue, numbers_count):\n is_flip = False\n for command in function_command:\n if command == \"R\":\n is_flip = not is_flip\n if command == \"D\":\n if len(queue) !=0:\n if is_flip is True:\n queue.pop()\n else:\n queue.popleft()\n else:\n return \"error\"\n if is_flip is True:\n queue.reverse()\n return queue\n\nmain()\n\n\n","repo_name":"KakaoFarm/oereo-algorithm","sub_path":"solved.ac/class3/AC.py","file_name":"AC.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10593491310","text":"import json\n\n\ndef get_load_json_data_all():\n with open(f'Data/bjj_overall.json', 'r') as f:\n file = json.load(f)\n\n return file\n\n\ndef get_list(name: str) -> dict:\n with open(f'Dictionaries/{name}.json', 'r') as f:\n file = json.load(f)\n\n sorted_list = sorted(file[name])\n\n options = []\n for key in sorted_list:\n options.append({'label': key, 'value': key})\n\n return options\n\n\ndef get_genders():\n return [\n {'label': 'Male', 'value': 'Male'},\n {'label': 'Female', 'value': 'Female'}\n ]","repo_name":"mbalcerzak/BJJ","sub_path":"dash_app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"14305403483","text":"import argparse\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\nimport torch\nimport torch.backends.cudnn\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom stacked_hourglass.datasets.mpii import Mpii, print_mpii_validation_accuracy\nfrom stacked_hourglass.train import do_validation_epoch, do_validation_step\n\n\ndef run_small_validation(model, num_batches, val_loader):\n i = 0\n\n progress = tqdm(val_loader, desc=f'Validation subset ({num_batches} batches)', total=num_batches, ascii=True,\n leave=True)\n\n for input, target, meta in progress:\n if i == num_batches:\n break\n\n target_weight = meta['target_weight']\n\n do_validation_step(model, input, target, Mpii.DATA_INFO, target_weight,\n flip=False)\n i += 1\n\n\ndef main(args):\n device = torch.device('cpu')\n\n # Disable gradient calculations.\n torch.set_grad_enabled(False)\n\n model = torch.jit.load(args.model_file)\n model = model.to(device)\n # Initialise the MPII validation set dataloader.\n val_dataset = Mpii(args.image_path, is_train=False)\n val_loader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n print(\"Warming the JIT model up...\")\n run_small_validation(model, num_batches=5, val_loader=val_loader)\n\n # Generate predictions for the validation set.\n _, _, predictions = do_validation_epoch(val_loader, model, device, Mpii.DATA_INFO, args.flip)\n\n # Report PCKh for the predictions.\n print('\\nFinal validation PCKh scores:\\n')\n print_mpii_validation_accuracy(predictions)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Evaluate a stacked hourglass model.')\n parser.add_argument('--image-path', required=True, type=str,\n help='path to MPII Human Pose images')\n # parser.add_argument('--arch', metavar='ARCH', default='hg1',\n # choices=['hg1', 'hg2', 'hg8'],\n # help='model architecture')\n parser.add_argument('--model-file', default='', type=str, metavar='PATH',\n help='path to saved model weights')\n parser.add_argument('--workers', default=4, type=int, metavar='N',\n help='number of data loading workers')\n parser.add_argument('--batch-size', default=6, type=int, metavar='N',\n help='batch size')\n parser.add_argument('--flip', dest='flip', action='store_true',\n help='flip the input during validation')\n\n main(parser.parse_args())\n","repo_name":"max810/CV701_assignment_4","sub_path":"src/evaluate_mpii.py","file_name":"evaluate_mpii.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30518404531","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the closestNumbers function below.\ndef closestNumbers(arr):\n arr = sorted(arr)\n minAbsDiff = min([abs(i-j) for i, j in zip(arr, arr[1:])])\n new_arr = []\n for x, y in zip(arr, arr[1:]):\n if abs(x-y)==minAbsDiff:\n if x Comment:\n poll = get_object(Poll, id=poll_id)\n group_user = group_user_permissions(group=poll.created_by.group.id, user=author_id)\n\n comment = comment_create(author_id=author_id,\n comment_section_id=poll.comment_section.id,\n message=message,\n parent_id=parent_id)\n\n poll_notification.create(sender_id=poll_id,\n action=poll_notification.Action.create,\n category='comment_all',\n message=f'User {group_user.user.username} replied to your comment '\n f'in poll {poll.title}',\n related_id=comment.id)\n\n if poll_notification.is_subscribed(user_id=comment.author_id, sender_id=poll_id, category='comment_self'):\n poll_notification.create(sender_id=poll_id,\n action=poll_notification.Action.create,\n category='comment_self',\n message=f'User {group_user.user.username} replied to your comment '\n f'in poll {poll.title}',\n related_id=comment.id,\n target_user_id=comment.author_id)\n\n return comment\n\n\ndef poll_comment_update(*, fetched_by: int, poll_id: int, comment_id: int, data) -> Comment:\n poll = get_object(Poll, id=poll_id)\n group_user_permissions(group=poll.created_by.group.id, user=fetched_by)\n\n return comment_update(fetched_by=fetched_by,\n comment_section_id=poll.comment_section.id,\n comment_id=comment_id,\n data=data)\n\n\ndef poll_comment_delete(*, fetched_by: int, poll_id: int, comment_id: int):\n poll = get_object(Poll, id=poll_id)\n group_user = group_user_permissions(group=poll.created_by.group.id, user=fetched_by)\n\n bypass = group_user_permissions(group_user=group_user, permissions=['admin', 'force_delete_comment'])\n\n return comment_delete(fetched_by=fetched_by,\n comment_section_id=poll.comment_section.id,\n comment_id=comment_id)\n","repo_name":"lokehagberg/flowback-backend","sub_path":"flowback/poll/services/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"73905791639","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport time\nimport random\n\nclass CreditCheck():\n def __init__(self, account_num, password):\n self.account_num = account_num\n self.password = password\n self.s = requests.session()\n self.headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Host': 'zhjw.scu.edu.cn',\n 'Referer': 'http://zhjw.scu.edu.cn/loginAction.do',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',\n 'Origin':'http://zhjw.scu.edu.cn',\n }\n\n # 登录教务处\n def login_in(self):\n url = 'http://zhjw.scu.edu.cn/loginAction.do'\n data = {\n 'zjh': self.account_num,\n 'mm': self.password\n }\n try:\n response = self.s.post(url, data = data, headers=self.headers) # 登录教务处\n except ConnectionError:\n print('网络连接登录错误')\n except TimeoutError:\n print('访问超时登录错误')\n\n isError = re.findall(r'', response.content.decode('gbk'))\n if isError: # 判断账号密码是否正确\n print('账号或者密码错误,请重新输入!')\n else:\n print('登录成功')\n\n # 显示用户名称 \n def show_user_name(self):\n url = 'http://zhjw.scu.edu.cn/menu/s_top.jsp'\n user_info = self.s.get(url, headers = self.headers) # 获取个人信息\n html = user_info.content.decode('gbk')\n user_name = re.findall(r'欢迎光临 .{0,6} ', html)\n try:\n user_name = user_name[0]\n num = user_name.rindex(' ')\n user_name = user_name[10: num]\n self.user_name = user_name\n print('你好,%s!' %(user_name)) # 显示个人信息\n except IndexError:\n print('获取信息失败')\n \n # 获取id\n def get_id(self):\n pattern = r'gradeLnAllAction.do\\?type\\=ln\\&oper=fainfo\\&fajhh=([0-9]{4})'\n url = 'http://202.115.47.141/gradeLnAllAction.do?type=ln&oper=fa'\n content = self.s.get(url=url, headers=self.headers).content.decode('GBK')\n id = re.findall(re.compile(pattern=pattern), content)[0]\n print('id', id)\n self.id = id\n\n # 获得学分信息\n def get_credit_info(self):\n url = 'http://202.115.47.141/gradeLnAllAction.do?type=ln&oper=lnfaqk&flag=zx'\n response = self.s.get(url, headers = self.headers)\n html = response.content.decode('gbk')\n print('---------------------')\n print(html)\n\n\ndef main():\n # account_num = str(input('请输入你的学号:'))\n # password = str(input('请输入你的教务处密码:'))\n # check = CreditCheck(account_num, password)\n check = CreditCheck('2016141442100', '081318')\n check.login_in()\n check.show_user_name()\n # check.get_id()\n check.get_credit_info()\n \nif __name__ == '__main__':\n main()\n","repo_name":"LoneWolfEric/Credit_Self_Check","sub_path":"credit_self_check.py","file_name":"credit_self_check.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28419706883","text":"import discord\nimport asyncio\nimport yaml\nimport asqlite\n\nfrom discord import TextChannel, ChannelType, Message, User\nfrom discord.ext import commands, menus\n\nfrom dataclasses import dataclass, field, replace\nfrom datetime import datetime, timezone\nfrom typing import Union, Optional, Dict, List\n\nfrom utils.funcs import guess_user_nitro_status, user_friendly_dt, create_embed, fix_url\n\n__all__ = [\n 'CustomContext',\n 'CustomBot',\n 'CustomMenu',\n 'Emotes',\n 'ReminderList',\n 'Reminder',\n 'BasicConfig',\n 'LoggingConfig',\n 'MissingAPIKey'\n]\n\n\nclass CustomContext(commands.Context):\n def __init__(self, **attrs):\n super().__init__(**attrs)\n self.bot: CustomBot = self.bot\n self.uncaught_error = False\n\n async def send(self, *args, **kwargs) -> Message:\n kwargs['reference'] = kwargs.get('reference', self.message.reference)\n\n return await super().send(*args, **kwargs)\n\n @property\n def basic_config(self):\n return self.bot.basic_configs.get(self.guild.id, BasicConfig(self.guild))\n\n @property\n def logging_config(self):\n return self.bot.logging_configs.get(self.guild.id, LoggingConfig(self.guild))\n\n\nclass CustomBot(commands.Bot):\n # noinspection PyTypeChecker\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n with open('config.yaml', 'r') as file:\n self.config = yaml.safe_load(file)\n\n self.reminders: Dict[int, Reminder] = {}\n self.basic_configs: Dict[int, BasicConfig] = {}\n self.logging_configs: Dict[int, LoggingConfig] = {}\n self.sniped: List[Message] = []\n self.cogs_list: List[str] = []\n\n self.fully_ready = False\n self.start_time: datetime = None # type: ignore\n self.db: asqlite.Connection = None # type: ignore\n self.session = None\n\n async def setup_hook(self):\n self.loop.create_task(self.startup())\n\n async def get_context(self, message: Message, *, cls=CustomContext) -> CustomContext:\n return await super().get_context(message, cls=cls)\n\n async def on_message(self, message):\n if not self.fully_ready:\n await self.wait_for('fully_ready')\n\n if message.content in [f'<@!{self.user.id}>', f'<@{self.user.id}>']:\n embed = create_embed(\n message.author,\n title='Bot has been pinged!',\n description='The current prefixes are: ' + ', '.join((await self.get_prefix(message))[1:])\n )\n\n await message.channel.send(embed=embed)\n\n await self.process_commands(message)\n\n async def startup(self):\n await self.wait_until_ready()\n\n self.start_time: datetime = datetime.now(timezone.utc)\n\n self.db: asqlite.Connection = await asqlite.connect('data.db', check_same_thread=False)\n\n await self.load_reminders()\n await self.load_basic_config()\n await self.load_logging_config()\n\n self.fully_ready = True\n self.dispatch('fully_ready')\n\n async def close(self):\n await self.db.close()\n await super().close()\n\n async def get_owner(self) -> User:\n if not self.owner_id and not self.owner_ids:\n info = await self.application_info()\n self.owner_id = info.owner.id\n\n return await self.fetch_user(self.owner_id or list(self.owner_ids)[0])\n\n async def load_reminders(self):\n async with self.db.cursor() as cursor:\n for row in await cursor.execute('SELECT * FROM reminders'):\n message_id: int = row['id']\n try:\n user: User = await self.fetch_user(row['user_id'])\n except discord.NotFound:\n user: None = None\n reminder: str = row['reminder']\n end_time: int = row['end_time']\n destination: Union[User, TextChannel] = self.get_channel(row['destination']) or user\n\n if destination is None or user is None:\n continue\n\n _reminder = Reminder(\n message_id=message_id,\n user=user,\n reminder=reminder,\n destination=destination,\n end_time=datetime.fromtimestamp(end_time, timezone.utc),\n bot=self\n )\n\n self.reminders[_reminder.id] = _reminder\n\n async def load_basic_config(self):\n async with self.db.cursor() as cursor:\n for row in await cursor.execute('SELECT * FROM basic_config'):\n guild = self.get_guild(row['guild_id'])\n prefix = row['prefix']\n snipe = bool(row['snipe'])\n mute_role = guild.get_role(row['mute_role']) if guild else None\n\n if not guild:\n continue\n\n config = BasicConfig(\n guild=guild,\n prefix=prefix,\n snipe=snipe,\n mute_role=mute_role\n )\n\n if row['mute_role'] and not mute_role:\n await cursor.execute('UPDATE basic_config SET mute_role = ? WHERE guild_id = ?', (None, guild.id))\n await self.db.commit()\n continue\n\n self.basic_configs[config.guild.id] = config\n\n async def load_logging_config(self):\n async with self.db.cursor() as cursor:\n for row in await cursor.execute('SELECT * FROM logging_config'):\n guild: discord.Guild = self.get_guild(row['guild_id'])\n\n if not guild:\n continue\n\n kick_channel = guild.get_channel(row['kick_channel'])\n ban_channel = guild.get_channel(row['ban_channel'])\n purge_channel = guild.get_channel(row['purge_channel'])\n delete_channel = guild.get_channel(row['delete_channel'])\n mute_channel = guild.get_channel(row['mute_channel'])\n\n config = LoggingConfig(\n guild=guild,\n kick_channel=kick_channel,\n ban_channel=ban_channel,\n purge_channel=purge_channel,\n delete_channel=delete_channel,\n mute_channel=mute_channel\n )\n\n self.logging_configs[config.guild.id] = config\n\n @staticmethod\n def get_custom_prefix(_bot: 'CustomBot', message: discord.Message):\n default_prefixes = ['doggie.', 'Doggie.', 'dog.', 'Dog.']\n\n if not message.guild:\n return commands.when_mentioned_or(*default_prefixes)(_bot, message)\n\n config = _bot.basic_configs.get(message.guild.id)\n\n if not config or not config.prefix:\n return commands.when_mentioned_or(*default_prefixes)(_bot, message)\n\n else:\n return commands.when_mentioned_or(config.prefix)(_bot, message)\n\n\nclass CustomMenu(menus.MenuPages):\n @menus.button('\\N{WASTEBASKET}\\ufe0f', position=menus.Last(3))\n async def do_trash(self, _):\n self.stop()\n await self.message.delete()\n\n def stop(self):\n self.call_end_event()\n super().stop()\n\n async def finalize(self, timed_out):\n self.call_end_event()\n\n def call_end_event(self):\n self.bot.dispatch('finalize_menu', self.ctx)\n\n\nclass Emotes:\n # Emotes available in https://discord.gg/Uk6fg39cWn\n\n bot_tag = '<:botTag:941816165221679144>'\n discord = '<:discord:941816357949960222>'\n owner = '<:owner:941816499960688650>'\n slowmode = '<:slowmode:941816507342651462>'\n check = '<:check:941816359090806804>'\n xmark = '<:xmark:941816519300616213>'\n role = '<:role:941816504318558208>'\n text = '<:channel:941816354393178172>'\n nsfw = '<:channel_nsfw:941816355995410432>'\n voice = '<:voice:941816520529571860>'\n emoji = '<:emoji_ghost:941816360059687043>'\n store = '<:store_tag:941816513097240656>'\n invite = '<:invite:941816364132368435>'\n partner = '<:partner:941816501248327700>'\n hypesquad = '<:hypesquad:941816362798559232>'\n nitro = '<:nitro:941816498681446460>'\n staff = '<:staff:941816508957483109>'\n balance = '<:balance:941816154681405481>'\n bravery = '<:bravery:941816350916096050>'\n brilliance = '<:brilliance:941816351721422869>'\n bughunter = '<:bughunter:941816353252323448>'\n supporter = '<:supporter:941816514506530856>'\n\n booster = '<:booster:941816158863102054>'\n booster2 = '<:booster2:941816160985440297>'\n booster3 = '<:booster3:941816161958527017>'\n booster4 = '<:booster4:941816163795603506>'\n verified = '<:verified:941816517710979162>'\n\n partnernew = '<:partnernew:941816502766690334>'\n members = '<:members:941816367466831983>'\n stage = '<:stagechannel:941816511692156928>'\n stafftools = '<:stafftools:941816510333202452>'\n thread = '<:threadchannel:941816516033269811>'\n mention = '<:mention:941816367466831983>'\n rules = '<:rules:941816505849491586>'\n news = '<:news:941816373062029332>'\n\n ban_create = '<:bancreate:941816156191346759>'\n ban_delete = '<:bandelete:941816157567070298>'\n member_leave = '<:memberleave:941816365772341298>'\n message_delete = '<:messagedelete:941816371401064490>'\n emote_create = '<:emotecreate:941816361561243700>'\n\n @staticmethod\n def channel(chann):\n if chann.type == ChannelType.text:\n if isinstance(chann, TextChannel):\n if chann.is_nsfw():\n return Emotes.nsfw\n return Emotes.text\n if chann.type == ChannelType.news:\n return Emotes.news\n if chann.type == ChannelType.voice:\n return Emotes.voice\n if chann.type == ChannelType.store:\n return Emotes.store\n if chann.type == ChannelType.category:\n return \"\"\n if str(chann.type).endswith('thread'):\n return Emotes.thread\n if chann.type == ChannelType.stage_voice:\n return Emotes.stage\n\n @staticmethod\n def badges(user):\n badges = []\n flags = [name for name, value in dict.fromkeys(iter(user.public_flags)) if value]\n\n if user.bot:\n badges.append(Emotes.bot_tag)\n if \"staff\" in flags:\n badges.append(Emotes.staff)\n if \"partner\" in flags:\n badges.append(Emotes.partner)\n if \"hypesquad\" in flags:\n badges.append(Emotes.hypesquad)\n if \"bug_hunter\" in flags:\n badges.append(Emotes.bughunter)\n if \"early_supporter\" in flags:\n badges.append(Emotes.supporter)\n if \"hypesquad_briliance\" in flags:\n badges.append(Emotes.brilliance)\n if \"hypesquad_bravery\" in flags:\n badges.append(Emotes.bravery)\n if \"hypesquad_balance\" in flags:\n badges.append(Emotes.balance)\n if \"hypesquad_brilliance\" in flags:\n badges.append(Emotes.brilliance)\n if \"verified_bot\" in flags:\n badges.append(Emotes.verified)\n if \"verified_bot_developer\" in flags:\n badges.append(Emotes.verified)\n\n if guess_user_nitro_status(user):\n badges.append(Emotes.nitro)\n\n return \" \".join(badges)\n\n\nclass ReminderList(menus.ListPageSource):\n async def format_page(self, menu, entries):\n index = menu.current_page + 1\n embed = create_embed(menu.ctx.author, title=f'Showing active reminders for {menu.ctx.author} '\n f'({index}/{self._max_pages}):')\n\n for reminder in entries:\n channel = reminder.destination if isinstance(reminder.destination, TextChannel) else None\n\n embed.add_field(name=f'ID: {reminder.id}',\n value=f'**Reminder:** {str(reminder)[:1100]}\\n'\n f'**Ends at:** {user_friendly_dt(reminder.end_time)}\\n'\n f'**Destination:** {channel.mention if channel else \"Your DMS!\"}\\n',\n inline=False)\n return embed\n\n\n@dataclass\nclass Reminder:\n message_id: int\n user: User\n reminder: str\n destination: Union[User, TextChannel]\n end_time: datetime\n bot: CustomBot\n id: int = field(init=False)\n task: asyncio.Future = field(init=False)\n\n def __post_init__(self):\n self.id = len(self.bot.reminders) + 1\n self.task = asyncio.ensure_future(self.send_reminder())\n self.bot.reminders[self.id] = self\n\n async def send_reminder(self):\n async with self.bot.db.cursor() as cursor:\n await cursor.execute(\n 'INSERT OR IGNORE INTO reminders VALUES (?, ?, ?, ?, ?)',\n (self.message_id,\n self.user.id,\n self.reminder,\n int(self.end_time.timestamp()),\n self.destination.id)\n )\n\n await self.bot.db.commit()\n await discord.utils.sleep_until(self.end_time)\n\n embed = discord.Embed(\n title='Reminder!',\n description=self.reminder,\n color=discord.Color.green()\n )\n\n if isinstance(self.destination, TextChannel):\n embed.set_footer(\n icon_url=fix_url(self.user.display_avatar),\n text=f'Reminder sent by {self.user}'\n )\n\n else:\n embed.set_footer(\n icon_url=fix_url(self.user.display_avatar),\n text=f'This reminder is sent by you!'\n )\n\n try:\n await self.destination.send(\n f\"**Hey {self.user.mention},**\" if isinstance(self.destination, TextChannel) else None,\n embed=embed\n )\n\n except (discord.Forbidden, discord.HTTPException):\n pass\n\n await self.remove()\n\n async def remove(self):\n async with self.bot.db.cursor() as cursor:\n await cursor.execute('DELETE FROM reminders WHERE id = (?)', (self.message_id,))\n await self.bot.db.commit()\n\n self.bot.reminders[self.id] = None\n self.task.cancel()\n\n def __str__(self):\n return self.reminder\n\n\n@dataclass(frozen=True)\nclass BasicConfig:\n guild: discord.Guild\n prefix: Optional[str] = None\n snipe: Optional[bool] = None\n mute_role: Optional[discord.Role] = None\n\n async def set_config(self, bot: CustomBot, **kwargs) -> 'BasicConfig':\n config = replace(self, **kwargs)\n\n async with bot.db.cursor() as cursor:\n await cursor.execute(\n 'REPLACE INTO basic_config VALUES(?, ?, ?, ?)',\n (\n config.guild.id,\n config.prefix,\n config.snipe,\n config.mute_role.id if config.mute_role else None\n )\n )\n\n await bot.db.commit()\n\n bot.basic_configs[config.guild.id] = config\n\n return config\n\n\n@dataclass(frozen=True)\nclass LoggingConfig:\n guild: discord.Guild\n kick_channel: Optional[TextChannel] = None\n ban_channel: Optional[TextChannel] = None\n purge_channel: Optional[TextChannel] = None\n delete_channel: Optional[TextChannel] = None\n mute_channel: Optional[TextChannel] = None\n\n async def set_config(self, bot: CustomBot, **kwargs) -> 'LoggingConfig':\n config = replace(self, **kwargs)\n\n async with bot.db.cursor() as cursor:\n await cursor.execute(\n 'REPLACE INTO logging_config VALUES(?, ?, ?, ?, ?, ?)',\n (\n config.guild.id,\n config.kick_channel.id if config.kick_channel else None,\n config.ban_channel.id if config.ban_channel else None,\n config.purge_channel.id if config.purge_channel else None,\n config.delete_channel.id if config.delete_channel else None,\n config.mute_channel.id if config.mute_channel else None\n )\n )\n\n await bot.db.commit()\n\n bot.logging_configs[config.guild.id] = config\n\n return config\n\n\nclass MissingAPIKey(commands.CommandError):\n pass\n","repo_name":"DoggieLicc/doggie-bot","sub_path":"utils/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":16170,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"10570023747","text":"import unittest\n\nfrom tkp.utility import coordinates\nfrom tkp.sourcefinder import extract\nfrom tkp.utility.uncertain import Uncertain\n\n\n# Specify the number of digits you want to include when checking if positions are equal.\nnod=12\n\nclass TestNCP(unittest.TestCase):\n \"\"\"\n Check that we retrieve the correct position for objects in images centred\n on the North Celestial Pole.\n\n At the NCP (dec=90), our coordinate system becomes ambiguous. We avoid the\n problem by subtracting an infintesimal quantity from the reference dec,\n such that it is never quite 90 degrees.\n\n See discussion at issue #4599.\n \"\"\"\n def test_3c61(self):\n # Coordinate system and position of 3C 61.1 based on an image of the\n # NCP provided by Adam Stewart.\n wcs = coordinates.WCS()\n wcs.ctype = ('RA---SIN', 'DEC--SIN')\n wcs.crval = (15.0, 90.0)\n wcs.cdelt = (-0.01111111111111, 0.01111111111111)\n wcs.crpix = (1025.0, 1025.0)\n wcs.unit = (\"deg\", \"deg\")\n calculated_position = wcs.p2s([908, 715])\n self.assertAlmostEqual(calculated_position[0], 35.7, 1)\n self.assertAlmostEqual(calculated_position[1], 86.3, 1)\n\n\nclass Sanity(unittest.TestCase):\n \"\"\"Some sanity checks because of issue #2787.\n\n Previously, 1 was added or subtracted in the\n pixel <-> sky conversion, resulting in positions\n being one pixel off in both x and y\n \"\"\"\n\n def setUp(self):\n self.wcs = coordinates.WCS()\n self.wcs.crota = [0, 0]\n self.wcs.cdelt = [1, 1]\n self.wcs.crpix = [10, 10]\n self.wcs.crval = [10, 10]\n\n def tests2p(self):\n x, y = self.wcs.s2p([10, 10])\n self.assertAlmostEqual(x, 10)\n self.assertAlmostEqual(y, 10)\n x, y = self.wcs.s2p([0, 0])\n self.assertAlmostEqual(x, 0)\n self.assertAlmostEqual(y, 0)\n x, y = self.wcs.s2p([1, 1])\n self.assertAlmostEqual(x, 1)\n self.assertAlmostEqual(y, 1)\n\n def testp2s(self):\n r, d = self.wcs.p2s([10, 10])\n self.assertAlmostEqual(r, 10)\n self.assertAlmostEqual(d, 10)\n r, d = self.wcs.p2s([0, 0])\n self.assertAlmostEqual(r, 0)\n self.assertAlmostEqual(d, 0)\n r, d = self.wcs.p2s([1, 1])\n self.assertAlmostEqual(r, 1)\n self.assertAlmostEqual(d, 1)\n\n\nclass wcsSin(unittest.TestCase):\n known_values = (\n ([1442.0, 1442.0], [350.785563529949, 58.848317299883],),\n ([1441.0, 1501.0], [350.85000000000002, 60.815406379421418],),\n ([1441.0, 1381.0], [350.85000000000002, 56.814593620578577],),\n ([1381.0, 1441.0], [354.70898191482644, 58.757358624100824],),\n ([1501.0, 1441.0], [346.99101808517361, 58.757358624100824],),\n )\n\n # \"header\" parameters for this test\n # (Taken from arbitrary FITS file)\n crval = (3.508500000000E+02, 5.881500000000E+01)\n crpix = (1.441000000000E+03, 1.441000000000E+03)\n cdelt = (-3.333333333333E-02, 3.333333333333E-02)\n ctype = ('RA---SIN', 'DEC--SIN')\n crota = (0, 0)\n cunit = ('deg', 'deg')\n\n def setUp(self):\n # Initialise a wcs object with the above parameters\n self.wcs = coordinates.WCS()\n self.wcs.crval = self.crval\n self.wcs.crpix = self.crpix\n self.wcs.cdelt = self.cdelt\n self.wcs.ctype = self.ctype\n self.wcs.crota = self.crota\n self.wcs.cunit = self.cunit\n\n def testPixelToSpatial(self):\n for pixel, spatial in self.known_values:\n result = self.wcs.p2s(pixel)\n self.assertEqual([round(result[0],nod),round(result[1],nod)], [round(spatial[0],nod),round(spatial[1],nod)])\n\n def testSpatialToPixel(self):\n for pixel, spatial in self.known_values:\n result = list(map(round, self.wcs.s2p(spatial)))\n self.assertEqual(result, pixel)\n\n def testSanity(self):\n import random\n pixel = [random.randrange(500, 1500), random.randrange(500, 1500)]\n result = list(map(round, self.wcs.s2p(self.wcs.p2s(pixel))))\n self.assertEqual(result, pixel)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"transientskp/tkp","sub_path":"tests/test_utility/test_wcs.py","file_name":"test_wcs.py","file_ext":"py","file_size_in_byte":4120,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"85"} +{"seq_id":"2899249246","text":"\"\"\"\n开设进程\n 1、申请内存空间 耗资源\n 2、”拷贝代码“ 耗资源\n\n开线程\n 一个进程内可以开设多个线程,在用一个进程内开始多个线程\n 无需再次申请内存空间\n\n总结:开设进程的开销要远远的小于进程的开销\n\n例如:我们要开发一款文本编辑器\n 获取用户输入的功能\n 实时展示到屏幕的功能\n 自动保存到硬盘功能\n针对上面三个功能,开设进程还是线程合适?\n 开三个线程处理\n\"\"\"\nfrom threading import Thread\nimport time\n\n\"\"\"\ndef task(name):\n print('%s is running' % name)\n time.sleep(2)\n print('%s is over' % name)\n\n\n# 开启线程不需要在main下面执行代码,直接书写就可以\n# 但是习惯上将启动命令写在main下面\nif __name__ == '__main__':\n t = Thread(target=task, args=('egon', ))\n t.start()\n print('主')\"\"\"\n\n\n\nclass MyThread(Thread):\n def __init__(self, name):\n self.name = name\n # 重写了别人的方法 又不知道别人的方法里有啥 你就调用父类的方法\n super().__init__()\n\n def task(name):\n print('%s is running' % name)\n time.sleep(2)\n print('%s is over' % name)\n\n\nif __name__ == '__main__':\n t = MyThread('egon')\n t.start()\n print('主')","repo_name":"OPBrother/LearningPython","sub_path":"ljy_16并发编程/ljy_11线程.py","file_name":"ljy_11线程.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33740021160","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 9 16:05:14 2018\n\n@author: arnik\n\"\"\"\n\ndef TowerOfHanoi(n,From,To,Aux):\n #base condition\n if(n == 1):\n print(\"Move disk \",n,\"from \",From,\"tower to\",To,\"tower\")\n \n else:\n TowerOfHanoi(n-1,From,Aux,To)\n print(\"Move disk \",n,\"from \",From,\"tower to\",To,\"tower\")\n TowerOfHanoi(n-1,To,Aux,From)\n \ndef main():\n n=int(input(\"Enter the number of disk: \"))\n print(\"The moves are : \\n\")\n TowerOfHanoi(n,\"A\",\"B\",\"C\")\n \nmain()","repo_name":"arnika13/Programming_Challenges","sub_path":"Python_Programs/towerofhanoi.py","file_name":"towerofhanoi.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15865197195","text":"class Player():\n def __init__(self, player_id, last_name, first_name, bats, throws, team,\n pos):\n self.player_id = player_id\n self.last_name = last_name\n self.first_name = first_name\n self.bats = bats\n self.throws = throws\n self.team = team\n self.pos = pos\n\n def __repr__(self):\n return self.pos + \" - \" + self.first_name + \" \" + self.last_name + \" \" \\\n + self.bats + \"/\" + self.throws\n","repo_name":"michaeldressner/mlb-tools","sub_path":"play_by_play/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21870328984","text":"from itertools import product, permutations, combinations, combinations_with_replacement, accumulate, groupby, count, cycle, repeat\nimport operator\n\n\nls_a = [1, 2]\nls_b = [3, 4]\n\nprod = product(ls_a, ls_b) # product function will calculate the catersian product of the passed arguments\n# print(prod) # it will create the itertools object so we need to convert it into an iterable\n\n# print(tuple(prod))\n# print(list(prod))\n\n\ntp_a = (1, 2)\ntp_b = (3,)\n\nprod = product(tp_a, tp_b, repeat=3) \n\n# print(tuple(prod))\n# print(list(prod))\n\n\n\n\n\n\n\nls_1 = [1, 2, 3]\nperm = permutations(ls_1,) # permutation is each of several possible ways in which a set or number of things can be ordered or arranged.\n# print(list(perm))\n\n\nls_1 = [1, 2, 3]\nperm = permutations(ls_1, r=2) # defining no. of permutations using r as argument in permutation function\n# print(list(perm))\n\n\n\n\n\n\n\n\nls_2 = [1, 2, 3, 4, 5] # it makes combinations without repeated values\ncomb = combinations(ls_2, r=2) # defining no. of permutations using r as argument in combinatin function is a must\n# print(list(comb))\n\ncomb_wr = combinations_with_replacement(ls_2, r=2) # it includes repeated values, it is opposite of (combinations) \n# print(list(comb_wr))\n\n\n\n\n\n\nls_3 = [1, 2, 3, 4]\nacum = accumulate(ls_3) # it is used to get the accumulated sum of elements of iterable\n# print(list(acum))\n\n# print(accumulate.__doc__)\n\nls_3 = [1, 2, 3, 4]\nacum = accumulate(ls_3, func=operator.mul) \nprint(list(acum))\n\nls_3 = [1, 2, 5, 3, 4 ]\nacum = accumulate(ls_3, func=max) \nprint(list(acum))\n\n\n\n\n\n\n\n\n\ndef smaller_than_3(x):\n return x < 3\n\nls_4 = [1, 2, 3, 4]\ngroup_obj = groupby(ls_4, key=smaller_than_3)\nfor key,value in group_obj:\n print(key, list(value))\n\n\n\npersons = [{'name':'sajjal', 'age':23}, {'name':'malik','age':23}, {'name':'john','age':22}, {'name':'ripper','age':21}]\ngroup_obj = groupby(persons, key=lambda x: x['age'])\nfor key,value in group_obj:\n print(key, list(value))\n\n\n\n\n\n\n\n# for i in count(10, 2):\n# print(i)\n# if i == 16:\n# break\n\n\n# ls = [1, 2, 3]\n# for i in cycle(ls):\n # print(i)\n\n# for i in repeat(2, 4):\n# print(i)\n\n\n\n\n","repo_name":"Sajjal-Malik/Python-Intermediate-Topics","sub_path":"Itertools.py","file_name":"Itertools.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34545961467","text":"class library:\r\n books={'python':10,'java':5,'webtech':8,'sql':16,'django':20}\r\n def __init__(self,cname):\r\n self.cname=cname\r\n self.nob=0\r\n self.books={}\r\n\r\n def main(self):\r\n print()\r\n op=input('Enter 1 to display the library books \\nEnter 2 to display your details \\nEnter 3 to borrow a book \\nEnter 4 to return a book \\nEnter 5 to exit \\n-->')\r\n if op=='1':\r\n self.library_books()\r\n self.main()\r\n elif op=='2':\r\n self.display_c_details()\r\n self.main()\r\n elif op=='3':\r\n self.borrow_book()\r\n self.main()\r\n elif op=='4':\r\n self.return_book()\r\n self.main()\r\n elif op=='5':\r\n print('Thanks... Visit Again')\r\n return\r\n else:\r\n print('Invalid Input')\r\n self.main()\r\n\r\n @classmethod\r\n def library_books(cls):\r\n print (\"Books in library are:\")\r\n print(\"Book Name\",\"No.of Books Available\",sep=\"\\t\")\r\n for i in library.books:\r\n print(f'{i}',f'{library.books[i]}',sep='\\t\\t\\t')\r\n\r\n def display_c_details(self):\r\n print (f'Name: {self.cname}')\r\n if self.books!={}:\r\n print (f'No. of books taken: {self.nob}')\r\n print('Your books are :')\r\n c=1\r\n for b in self.books:\r\n print(f'{c} : {b}')\r\n c+=1\r\n else:\r\n print('No Books Borrowed..')\r\n\r\n def borrow_book(self):\r\n if self.nob<4:\r\n bname=input('Enter the book name:')\r\n if bname in library.books:\r\n if bname not in self.books:\r\n if library.books [bname]>0:\r\n library.books [bname] -=1\r\n print('Successfully borrowed')\r\n self.nob+=1\r\n self.books[bname]=1\r\n else:\r\n print ('Sorry... Currently This Book is not available.')\r\n else:\r\n print('You are not supposed to take the same book more than once...')\r\n else:\r\n print('Sorry... No such book is available in our Library.')\r\n else:\r\n print('Limit Exceeded')\r\n\r\n def return_book(self):\r\n if self.nob>0:\r\n bname=input('Enter a book name :')\r\n if bname in library.books:\r\n if bname in self.books:\r\n print('Returned Successfully...')\r\n self.nob-=1\r\n library.books[bname]+=1\r\n self.books.pop(bname)\r\n else:\r\n print(\"Sorry... You didn't take this book from our library..\") \r\n else:\r\n print('Sorry... This book is not belong to us..')\r\n else:\r\n print('No Books borrowed ... please borrow one to return')\r\n \r\nprint('*********************** WELCOME TO ADVANCED LIBRARY MANAGEMENT SYSTEM OF ABC COLLEGE ***********************')\r\nl1=library('raj')\r\nl1.main()\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":"AGORA16/Library_Management_System","sub_path":"library_management_system.py","file_name":"library_management_system.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42347171124","text":"from django.urls import path, include\nfrom .views import (\n LoginView,\n CustomUserRegistrationView,\n UserProfileView,\n)\nfrom rest_framework.routers import DefaultRouter\n\nrouter = DefaultRouter(trailing_slash=False)\nrouter.register(\"profile\", UserProfileView)\n\n\nurlpatterns = [\n path('', include(router.urls)),\n path('login', LoginView.as_view(), name=\"login\"),\n path('register', CustomUserRegistrationView.as_view(), name=\"register\"),\n]","repo_name":"uchqunusmonov/Django-React-Chat","sub_path":"users/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"787214575","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.db.utils import IntegrityError\nfrom scraper.scraper import scrape_recipes\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.decorators import api_view\nfrom .models import Search, Recipe, Profile\nfrom .serializers import RecipeSerializer, UserSerializer\n\n\ndef test_route(request):\n\treturn JsonResponse({'message': 'route is working'})\n\ndef search(request, query):\n\tquery = query.replace(\"+\", \" \")\n\texisting_results = Search.objects.filter(search_term=query)\n\tif len(existing_results) == 0:\n\t\trecipes = []\n\t\tnew_recipes = scrape_recipes(query, 5)\n\t\tfor recipe in new_recipes:\n\t\t\tobj, created = Recipe.objects.get_or_create(\n\t\t\t\turl=recipe[\"url\"],\n\t\t\t\tdefaults={\n\t\t\t\t\t\"title\": recipe[\"title\"],\n\t\t\t\t\t\"ingredients\": recipe[\"ingredients\"],\n\t\t\t\t\t\"instructions\": recipe[\"instructions\"]\n\t\t\t\t})\n\t\t\tSearch.objects.create(\n\t\t\t\tsearch_term=query,\n\t\t\t\trecipe=obj\n\t\t\t)\n\t\t\trecipes.append(RecipeSerializer(obj).data)\n\t\tif recipes:\n\t\t\treturn JsonResponse({\n\t\t\t\t\"message\": \"recipes added to database\",\n\t\t\t\t\"data\": recipes,\n\t\t\t\t\"status\": 201\n\t\t\t\t})\n\t\telse:\n\t\t\treturn JsonResponse({\n\t\t\t\t\"message\": \"Search returned no results.\",\n\t\t\t\t\"data\": [],\n\t\t\t\t\"status\": 200\n\t\t\t\t})\n\telse:\n\t\trecipes = [RecipeSerializer(result.recipe).data for result in existing_results]\n\t\treturn JsonResponse({\n\t\t\t\"message\": \"recipes retrieved from database\",\n\t\t\t\"data\": recipes,\n\t\t\t\"status\": 200\n\t\t\t})\n\n@api_view([\"POST\"])\ndef register(request):\n\ttry:\n\t\tuser = User.objects.create_user(\n\t\t\tusername=request.data[\"username\"],\n\t\t\temail=request.data[\"email\"],\n\t\t\tpassword=request.data[\"password\"]\n\t\t)\n\t\tprofile = Profile.objects.create(\n\t\t\tuser=user\n\t\t)\n\t\tlogin(request, user)\n\t\treturn JsonResponse({\n\t\t\t\"message\": \"User created.\",\n\t\t\t\"data\": UserSerializer(user).data,\n\t\t\t\"status\": 201\n\t\t\t}) \n\texcept IntegrityError:\n\t\treturn JsonResponse({\n\t\t\t\"message\": \"User already exists\",\n\t\t\t\"status\": 401\n\t\t\t})\n\ndef get_logged_in_user(request):\n\tif request.user.is_authenticated:\n\t\treturn JsonResponse({\n\t\t\t\"message\": \"user is logged in\",\n\t\t\t\"data\": UserSerializer(request.user).data,\n\t\t\t\"status\": 200\n\t\t\t})\n\telse:\n\t\treturn JsonResponse({\n\t\t\t\"data\": {},\n\t\t\t\"message\": \"No user is currently logged in\",\n\t\t\t\"status\": 401\n\t\t\t})\n\ndef log_out(request):\n\tlogout(request)\n\treturn JsonResponse({\n\t\t\"data\": {},\n\t\t\"message\": \"Logged out.\",\n\t\t\"status\": 200\n\t\t})\n\n@api_view([\"POST\"])\ndef log_in(request):\n\tuser = authenticate(\n\t\tusername=request.data[\"username\"],\n\t\tpassword=request.data[\"password\"]\n\t)\n\tif user is not None:\n\t\tlogin(request, user)\n\t\treturn JsonResponse({\n\t\t\t\"message\": \"user logged in\",\n\t\t\t\"data\": UserSerializer(user).data,\n\t\t\t\"status\": 200\n\t\t\t})\n\telse:\n\t\treturn JsonResponse({\n\t\t\t\"message\": \"Invalid username or password\",\n\t\t\t\"data\": {},\n\t\t\t\"status\": 401\n\t\t\t})","repo_name":"MattKeane/Chef-Hopper","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28243993394","text":"from Engine.vector import Vector\nfrom Engine.camera import Camera\nfrom Engine.vertex import Vertex\nfrom Engine.mesh import Mesh\nfrom Engine.face import Face\nfrom Engine.object3D import Object3D\nfrom Engine.meshes.cube import Cube\nfrom Engine.force import Force\n\nimport random\n\nclass Creature(Cube):\n def __init__(self, engine, x, y, z, color=(255,0,0)):\n Cube.__init__(self, engine, x, y, z, 1, color, True)\n self.day = 0\n self.tick = 0\n self.maxTick = 2\n\n def Update(self):\n Cube.Update(self)\n #if (self.day >= 120): #cely den\n\n if (self.tick >= self.maxTick):\n self.mesh.changeColor((0,255,0))\n \n\n self.tick += self.deltaTime \n self.checkPosition()\n\n def Draw(self, screen):\n Cube.Draw(self, screen)\n\n def checkPosition(self):\n if (self.Position.x <= -1000):\n self.removeAll()\n self.Position = Vector(0,20,0)\n if (self.Position.y <= -1000):\n self.t = 0\n self.removeAll()\n self.Position = Vector(0,20,0)\n if (self.Position.x >= 1000):\n self.removeAll()\n self.Position = Vector(0,20,0)\n if (self.Position.y >= 1000):\n self.removeAll()\n self.Position = Vector(0,20,0)\n\n def removeAll(self):\n Object3D.removeAllForces(self)\n","repo_name":"KubaBoi/Snejky","sub_path":"Snejky/creature.py","file_name":"creature.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"75111421397","text":"import requests\nfrom ..db import con\nfrom ..utils import relative_to\nfrom datetime import date\nfrom .ServicioEventos import prevision_clima\nfrom .FuncionesCompartidas import TiempoParaEventos\n\ndef climaDia(coordenadas):\n if coordenadas == \"42.3443701,-3.6927629\" or coordenadas == \"42.34995,-3.69205\":\n coordenadas = \"41.6704100,-3.6892000\"\n\n datosObtenidos = requests.get(\n \"https://api.tutiempo.net/json/?lan=es&&units=Metric&apid=XwY44q4zaqXbxnV&ll=\"\n + coordenadas\n )\n datosFormatonJSON = datosObtenidos.json()\n\n dias = []\n dias.append(datosFormatonJSON.get(\"day2\"))\n dias.append(datosFormatonJSON.get(\"day3\"))\n dias.append(datosFormatonJSON.get(\"day4\"))\n dias.append(datosFormatonJSON.get(\"day5\"))\n dias.append(datosFormatonJSON.get(\"day6\"))\n dias.append(datosFormatonJSON.get(\"day7\"))\n\n if None in dias:\n return None\n\n lista = []\n url = \"https://v5i.tutiempo.net\"\n wd, wi = f\"{url}/wd/big/black/\", f\"{url}/wi/\"\n wi_icon = wi + \"{style}/{size}/{icon}.png\"\n wd_icon = wd + \"{icon}.png\"\n\n for d in dias:\n date = d.get(\"date\")\n temp_min = d.get(\"temperature_min\")\n temp_max = d.get(\"temperature_max\")\n icono = d.get(\"icon\")\n viento = d.get(\"wind\")\n icono_viento = d.get(\"icon_wind\")\n\n info = {\n \"fecha\": date,\n \"temp_min\": temp_min,\n \"temp_max\": temp_max,\n \"icono\": icono,\n \"viento\": viento,\n \"icono_viento\": icono_viento,\n \"wi_icon\": wi_icon,\n \"wd_icon\": wd_icon,\n }\n\n lista.append(info)\n\n return lista\n\n\ndef ActualizarTiempoEventos(id):\n cur = con.cursor()\n cur.execute(\"SELECT DISTINCT Ciudad FROM EventosFavoritos WHERE IdUsuario=?\", (id,))\n resul = cur.fetchall()\n\n for tupla in resul:\n for ciudad in tupla:\n cur.execute(\n \"SELECT Latitud,Longitud FROM Ubicaciones WHERE Ciudad=?\", (ciudad,)\n )\n infocity = cur.fetchall()\n\n if len(infocity) > 0:\n latitud = infocity[0][0]\n longitud = infocity[0][1]\n TiempoParaEventos(latitud, longitud, ciudad)\n con.commit()\n\n\ndef Preparese_Para_Su_Dia(city):\n lista = prevision_clima(city)\n datos = lista[2][0]\n info = {}\n\n today = date.today()\n fecha = today.strftime(\"%a, %d %b %Y\")\n paraguas = \"No es necesario\"\n abrigo = \"Ropa fina\"\n sensacion_termica = datos.get(\"temp\")\n al_aire_libre = datos.get(\"descripcion\")\n temp = datos.get(\"temp\")\n temp = temp.split(\"º\", 1)\n\n if datos.get(\"lluvia\") > 30:\n paraguas = \"Es necesario\"\n if int(temp[0]) < 14:\n abrigo = \"Ropa gruesa\"\n if int(temp[0]) > 23:\n abrigo = \"Ropa de verano\"\n\n info = {\n \"paraguas\": paraguas,\n \"abrigo\": abrigo,\n \"sensTermica\": sensacion_termica,\n \"aireLibre\": al_aire_libre,\n \"fecha\": fecha,\n }\n\n return info","repo_name":"jmri1001/PROYECTO_TFG","sub_path":"src/servicios/ServicioMeteorologia.py","file_name":"ServicioMeteorologia.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"75198777236","text":"nome_corretor = input(\"Digite o nome do corretor: \")\r\n\r\n\r\n\r\nquantidade_imoveis_vendidos = int(input(\"Digite a quantidade de imóveis vendidos: \"))\r\n\r\n\r\n\r\nvalor_total_vendas = float(input(\"Digite o valor total das vendas: \"))\r\n\r\n\r\n\r\nsalario_base = 1500.00\r\n\r\n\r\n\r\ncomissao_por_imovel = 200.00\r\n\r\n\r\nporcentagem_comissao = 0.05\r\n\r\n\r\n\r\ncomissao_total = quantidade_imoveis_vendidos * comissao_por_imovel + valor_total_vendas * porcentagem_comissao\r\n\r\n\r\n\r\nsalario_final = salario_base + comissao_total\r\n\r\nprint(f\"O salário final do corretor {nome_corretor} é: R$ {salario_final:.2f}\")","repo_name":"GabrielaKP05/AulaPythonexercicios","sub_path":"corretora2.py","file_name":"corretora2.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"15581160100","text":"import time\nimport numpy as np\nimport faiss\n\n__all__ = ['Kmeans', 'cluster_assign', 'arrange_clustering']\n\nclass ReassignedDataset:\n \"\"\"A dataset where the new patients labels are given in argument.\n Args:\n patient_indexes (list): list of data indexes\n pseudolabels (list): list of labels for each data\n dataset (list): list of tuples with paths to patients\n \"\"\"\n\n def __init__(self, patient_indexes, pseudolabels, dataset):\n self.ptns = self.make_dataset(patient_indexes, pseudolabels, dataset)\n \n \n def make_dataset(self, patient_indexes, pseudolabels, dataset):\n patients = []\n for j, idx in enumerate(patient_indexes):\n patients.append(([dataset[i][idx] for i in range(4)], pseudolabels[j]))\n return patients\n \n\n def __len__(self):\n return len(patients)\n\ndef cluster_assign(patients_lists, dataset):\n \"\"\"Creates a dataset from clustering, with clusters as labels.\n Args:\n patients_lists (list of list): for each cluster, the list of patient indexes\n belonging to this cluster\n dataset (list): initial dataset\n Returns:\n ReassignedDataset: a dataset with clusters as labels\n \"\"\"\n assert patients_lists is not None\n pseudolabels = []\n patient_indexes = []\n for cluster, patients in enumerate(patients_lists):\n patient_indexes.extend(patients)\n pseudolabels.extend([cluster] * len(patients))\n\n return ReassignedDataset(patient_indexes, pseudolabels, dataset)\n\ndef run_kmeans(x, nmb_clusters, verbose=False):\n \"\"\"Runs kmeans on multiple GPU.\n Args:\n x: data\n nmb_clusters (int): number of clusters\n Returns:\n list: ids of data in each cluster\n \"\"\"\n n_data, d = x.shape\n\n # faiss implementation of k-means\n \n clus = faiss.Clustering(d, nmb_clusters) \n clus.seed = 42\n clus.niter = 20\n clus.max_points_per_centroid = 10000000\n \n #CPU index\n index = faiss.IndexFlatL2(d)\n\n # perform the training\n clus.train(x, index)\n _, I = index.search(x, 1)\n stats = clus.iteration_stats\n losses = np.array([stats.at(i).obj for i in range(stats.size())])\n if verbose:\n print('k-means loss evolution: {0}'.format(losses))\n\n return [int(n[0]) for n in I], losses[-1]\n\ndef arrange_clustering(patients_lists):\n pseudolabels = []\n patient_indexes = []\n for cluster, patients in enumerate(patients_lists):\n patient_indexes.extend(patients)\n pseudolabels.extend([cluster] * len(patients))\n indexes = np.argsort(patient_indexes)\n return np.asarray(pseudolabels)[indexes]\n\n\nclass Kmeans(object):\n def __init__(self, k):\n self.k = k\n\n def cluster(self, data, verbose=False):\n \"\"\"Performs k-means clustering.\n Args:\n x_data (np.array N * dim): data to cluster\n \"\"\"\n end = time.time()\n\n # cluster the data\n I, loss = run_kmeans(data, self.k, verbose)\n self.patients_lists = [[] for i in range(self.k)]\n for i in range(len(data)):\n self.patients_lists[I[i]].append(i)\n\n if verbose:\n print('k-means time: {0:.0f} s'.format(time.time() - end))\n\n return loss\n","repo_name":"vsubbian/SLAC-Time","sub_path":"SLAC-Time_MultiMode/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"39592498140","text":"# 숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 가지고 있는지 아닌지를 구하는 프로그램을 작성하시오.\n\nn = int(input())\nn_arr = sorted(list(map(int,input().split())))\nm = int(input())\nm_arr = list(map(int, input().split()))\n\nfor i in range(m):\n s = 0\n e = n - 1\n flag = False\n while s <= e:\n mid = (s+e)//2\n if m_arr[i] > n_arr[mid]:\n s = mid + 1\n elif m_arr[i] < n_arr[mid]:\n e = mid - 1\n else:\n flag = True\n print(1)\n break\n if flag == False:\n print(0)\n","repo_name":"ksunbum97/algorithm_test","sub_path":"백준/10815.py","file_name":"10815.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"25066108169","text":"##REST EXAMPLE 2\n\nimport random\nimport string\nimport cherrypy\n\nclass StringGeneratorWebService(object):\n exposed = True\n\n def GET(self,*path,**query):\n #URI can be managed as a String\n return (\"uri: %s; urilength: %s\" %(str(path),len(path)))\n\n def POST(self,*path,**query):\n some_string = ''.join(random.sample(string.hexdigits,int(query['length'])))\n cherrypy.session['mystring'] = some_string\n return some_string\n\n def PUT(self,*path,**query):\n cherrypy.session['mystring']=params['another_string']\n\n def DELETE(self,*path,**query):\n cherrypy.session.pop('mystring', None)\n\nif __name__==\"__main__\":\n conf = {\n '/': {\n 'request.dispatch':cherrypy.dispatch.MethodDispatcher(),\n 'tools.sessions.on':True\n }\n }\n cherrypy.tree.mount(StringGeneratorWebService(),'/string',conf)\n\n cherrypy.config.update({'server.socket_host':'0.0.0.0'})\n cherrypy.config.update({'server.socket_port':8080})\n \n cherrypy.engine.start()\n cherrypy.engine.block() \n","repo_name":"OmarGai96/P4IoT_laboratories","sub_path":"ESE02/example2_REST.py","file_name":"example2_REST.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21393020861","text":"\"\"\"\nTrainer based on:\nhttps://github.com/Mjrovai/OpenCV-Face-Recognition/blob/master/FacialRecognition/02_face_training.py \n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport os\nimport re\n\n# Path to training image dataset\npath = f'datasets{os.sep}private'\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\ndetector = cv2.CascadeClassifier(f'haar_cascades{os.sep}haarcascade_frontalface_default.xml')\n\n# function to get the images and label data\ndef getImagesAndLabels(path):\n imagePaths = [os.path.join(path,f) for f in os.listdir(path)] \n faceSamples=[]\n ids = []\n for imagePath in imagePaths:\n PIL_img = Image.open(imagePath).convert('L') # convert to grayscale --> check if redundant as images already seem to be grayscale\n img_numpy = np.array(PIL_img,'uint8')\n id = int(re.search(r'(?:face-)(\\d+)(?:.*)', imagePath).group(1)) #NOTE: id.group(1) will return the full string matching\n faces = detector.detectMultiScale(img_numpy)\n for (x,y,w,h) in faces:\n faceSamples.append(img_numpy[y:y+h,x:x+w])\n ids.append(id)\n return faceSamples,ids\nprint (\"\\n [+] Training on dataset faces. It will take a few seconds. Wait ...\")\nfaces,ids = getImagesAndLabels(path)\nrecognizer.train(faces, np.array(ids))\n# Save the model into trainer/trainer.yml\nrecognizer.write(f'trainer{os.sep}private{os.sep}trainer.yml') \n# Print the numer of faces trained and end program\nprint(f\"\\n [+] {len(ids)} faces trained. Exiting Program\")","repo_name":"lasupernova/security_cam_AI","sub_path":"train_on_data.py","file_name":"train_on_data.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"73401595799","text":"from django.contrib import admin\nfrom django.conf.urls import *\nfrom django.urls import path\nfrom HelloWorld import view, testdb, search, search2\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('hello/', view.hello),\n path('hello2/', view.hello2),\n url(r'^$', view.hello),\n url(r'^testdb$', testdb.testdb),\n url(r'^search-form$', search.search_form),\n url(r'^search$', search.search),\n url(r'^search-post$', search2.search_post),\n]\n","repo_name":"MrWJB/rtxs","sub_path":"rtxs/HelloWorld/HelloWorld/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21315535240","text":"from __future__ import absolute_import\nimport sys\nimport logging\n\nLOG_LEVELS = {\n \"CRITICAL\": logging.CRITICAL,\n \"ERROR\": logging.ERROR,\n \"WARNING\": logging.WARNING,\n \"INFO\": logging.INFO,\n \"DEBUG\": logging.DEBUG\n}\n\n\ndef get_log_level(level):\n return LOG_LEVELS.get(level, logging.INFO)\n \n\ndef set_log_level(level):\n loglevel = LOG_LEVELS.get(level, logging.INFO)\n logging.basicConfig(level=loglevel)\n \n\nnotify_logger = logging.getLogger('notify')\n\n\ndef notify_error(message):\n notify_logger.error(message)\n\n\ndef notify_exception(request, message=None, details=None, exec_info=None):\n \"\"\"\n :param request: a Django request object\n :param message: message string\n :param details: dict with additional details to be included in the output\n \"\"\"\n if request is not None:\n message = message or request.path\n notify_logger.error(\n 'Notify Exception: %s' % (message\n or \"No message provided, fix error handler\"),\n exc_info=exec_info or sys.exc_info(),\n extra={\n 'status_code': 500,\n 'request': request,\n 'details': details,\n }\n )\n\n\ndef log_signal_errors(signal_results, message, details):\n for result in signal_results:\n # Second argument is None if there was no error\n return_val = result[1]\n if return_val and isinstance(return_val, Exception):\n notify_exception(\n None,\n message=message % return_val.__class__.__name__,\n details=details,\n exec_info=(type(return_val), return_val, return_val.__traceback__)\n )\n\n\ndef notify_js_exception(request, message=None, details=None):\n notify_logger.error(\n 'Notify JS Exception: {}'.format(message),\n extra={\n 'request': request,\n 'details': details,\n }\n )\n\n\ndef get_traceback(limit):\n from cStringIO import StringIO\n import traceback\n f = StringIO()\n traceback.print_stack(file=f, limit=15 + limit)\n lines = f.getvalue().strip().split('\\n')\n count = 2\n for line in reversed(lines[:-2 * count]):\n if not line.lstrip().startswith(\"File\"):\n continue\n elif '/restkit/' in line or '/couchdbkit/' in line:\n count += 1\n else:\n break\n\n end = -2 * count\n start = -2 * (count + limit)\n\n return \"{traceback}\\n[plus {skipped} other frames]\".format(\n traceback='\\n'.join(lines[start:end]),\n skipped=count,\n )\n","repo_name":"dimagi/dimagi-utils","sub_path":"dimagi/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"85"} +{"seq_id":"15124053774","text":"#!/usr/bin/env python3\n\n\nimport errno\n# Included modules\nimport os\nimport signal\nimport sys\nimport threading\nfrom subprocess import PIPE, Popen\nfrom time import sleep\n\n\ndef mkdirp(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\nprocesses = []\nthreads = []\n\n\ndef signal_handler(signal, frame):\n print('- Exiting ZeroNet...')\n global processes, threads\n for process in processes:\n try:\n process.terminate()\n except OSError as err:\n if err.errno != errno.ESRCH:\n print(\"- Error while killing the process: \" + err.errno)\n process.wait()\n for thread in threads:\n thread.join()\n\n\ndef setarg(arg, val):\n if arg not in sys.argv:\n if len(val):\n sys.argv = [sys.argv[0]] + [arg, val] + sys.argv[1:]\n else:\n sys.argv = [sys.argv[0]] + [arg] + sys.argv[1:]\n\n\nclass pipeThread (threading.Thread):\n def __init__(self, threadID, name, counter, args):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n self.args = args\n\n def run(self):\n # print \"Starting \"+self.name\n self.args.communicate()\n print(self.name + \" has exited\")\n\n\ndef start_tor(args):\n argv = [os.environ['SNAP'] + \"/command-tor.wrapper\"] + args[0:]\n global threads, process\n process = Popen(argv)\n tor_thread = pipeThread(1, \"Tor\", 1, process)\n tor_thread.start()\n threads.append(tor_thread)\n processes.append(process)\n\n\ndef start_zero(args):\n global threads, processes\n process = Popen(args)\n zero_thread = pipeThread(2, \"ZeroNet\", 2, process)\n zero_thread.start()\n threads.append(zero_thread)\n processes.append(process)\n\n\ndef zero_plugins():\n #print(\"- Fixing plugins\")\n plugin_realsrc = os.environ['SNAP'] + \"/plugins\"\n plugin_src = \"/snap/zeronet/current/plugins\"\n plugin_dest = os.environ['SNAP_USER_COMMON'] + \"/plugins\"\n print(\"- Linking plugins...\")\n\n all_plugins = os.listdir(plugin_src)\n notfound = os.listdir(plugin_src)\n mkdirp(plugin_dest)\n current = os.listdir(plugin_dest)\n for pl in current: # check if that plugin exists, and remove it from notfound\n plp = plugin_dest + \"/\" + pl\n if os.path.islink(plp):\n pld = os.path.realpath(plp)\n # print \"Real of \"+plp+\" is \"+pld\n if pld.startswith(plugin_realsrc + \"/\"):\n if not os.path.exists(pld):\n print(\"WARNING: Unlinking %s!\" % plp)\n os.unlink(plp)\n pln = pld.replace(plugin_realsrc + \"/\",\n \"\").replace(\"disabled-\", \"\")\n if pln in notfound:\n notfound.remove(pln)\n if \"disabled-\" + pln in notfound:\n notfound.remove(\"disabled-\" + pln)\n\n for pl in notfound: # create that plugin link\n pld = plugin_dest + \"/\" + pl\n pls = plugin_src + \"/\" + pl\n if os.path.exists(pld):\n raise Exception(\n \"Path \" + pld + \" could not be linked to \" + pls + \": Already exists\")\n # print \"Linked \"+pls+\" to \"+pld\n os.symlink(pls, pld)\n\n\ndef link(src_):\n src = \"/snap/zeronet/current/\" + src_\n dst = os.environ['SNAP_USER_COMMON'] + \"/\" + src_\n if not os.path.exists(dst):\n os.symlink(src, dst)\n\n\ndef zero_link():\n for p in [\"update.py\", \"src\", \"zeronet.py\"]:\n link(p)\n\n\ndef zero_start():\n print(\"- Please report snap specific errors (e.g. Read-only file system) to: https://github.com/mkg20001/zeronet-snap/issues\")\n print(\"- and ZeroNet specific errors to: https://github.com/HelloZeroNet/ZeroNet/issues\")\n if \"--debug\" in sys.argv:\n print('[%s]' % ', '.join(map(str, sys.argv)))\n setarg(\"--data_dir\", os.environ['SNAP_USER_COMMON'] + \"/data\")\n setarg(\"--config_file\", os.environ['SNAP_USER_COMMON'] + \"/zeronet.conf\")\n setarg(\"--log_dir\", os.environ['SNAP_USER_COMMON'] + \"/log\")\n mkdirp(os.environ['SNAP_USER_COMMON'] + \"/data\")\n mkdirp(os.environ['SNAP_USER_COMMON'] + \"/log\")\n zero_plugins()\n zero_link()\n os.chdir(os.environ['SNAP_USER_COMMON'])\n sys.path.remove(os.environ[\"SNAP\"])\n sys.path.append(os.environ['SNAP_USER_COMMON'])\n sys.path.append(os.environ['SNAP_USER_COMMON'] + '/src')\n import zeronet\n sys.exit(zeronet.start())\n\n\ndef main():\n if \"--enable-tor\" in sys.argv:\n sys.argv.remove(\"--enable-tor\")\n setarg(\"--tor\", \"enable\")\n signal.signal(signal.SIGINT, signal_handler)\n signal.signal(signal.SIGTERM, signal_handler)\n start_tor([])\n start_zero(sys.argv)\n # This makes kill work, but only for 1 year TODO: fix this\n sleep(365 * 24 * 60 * 60 * 1000)\n else:\n zero_start()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ZeroNerds/zeronet-snap","sub_path":"src/scripts/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"85"} +{"seq_id":"24669131509","text":"import numpy as np\nfrom numpy import sin as s, cos as c, tan as t\nfrom drone_sim.sim.parameters import *\n\nclass Drone:\n def __init__(self, x=0, y=0, z=0.5, enable_death=True):\n # Position\n self.x, self.y, self.z = x, y, z\n\n # Roll Pitch Yaw\n self.phi, self.theta, self.psi = 0, 0, 0\n\n # Linear velocities\n self.vx, self.vy, self.vz = 0, 0, 0\n\n # Angular Velocities\n self.p, self.q, self.r = 0, 0, 0\n\n self.linear_position = lambda: np.array([self.x, self.y, self.z]).reshape(3, 1)\n self.angular_position = lambda: np.array([self.phi, self.theta, self.psi]).reshape(3, 1)\n self.linear_velocity = lambda: np.array([self.vx, self.vy, self.vz]).reshape(3, 1)\n self.angular_velocity = lambda: np.array([self.p, self.q, self.r]).reshape(3, 1)\n\n # Omegas\n self.w1 = 0\n self.w2 = 0\n self.w3 = 0\n self.w4 = 0\n\n # Inertia Matrix\n self.inertia = np.diag([IXX, IYY, IZZ])\n \n # Drag Matrix\n self.drag = np.diag([AX, AY, AZ])\n\n # Thrust Vector\n self.thrust = np.array(\n [\n [0],\n [0],\n [K*(self.w1**2 + self.w2**2 + self.w3**2 + self.w4**2)]\n ])\n\n # Torque Vector\n self.torque = np.array(\n [\n [L*K*(self.w1**2 - self.w3**2)],\n [L*K*(self.w2**2 - self.w4**2)],\n [B*(self.w1**2 - self.w2**2 + self.w3**2 - self.w4**2)]\n ]\n )\n # Drag Force Vector\n self.fd = -self.drag@self.linear_velocity()\n\n # Gravity Vector\n self.gravity = np.array([0, 0, -G]).reshape(-1, 1)\n\n # Transformation Matrices\n self.R_phi = np.array(\n [\n [c(self.phi), -s(self.phi), 0],\n [s(self.phi), c(self.phi), 0],\n [0, 0, 1]\n ]\n )\n\n self.R_theta = np.array(\n [\n [1, 0, 0],\n [0, c(self.theta), -s(self.theta)],\n [0, s(self.theta), c(self.theta)]\n ]\n )\n\n self.R_psi = np.array(\n [\n [c(self.psi), -s(self.psi), 0],\n [s(self.psi), c(self.psi), 0],\n [0, 0, 1]\n ]\n )\n\n self.R = self.R_phi @ self.R_theta @ self.R_psi\n\n self.W =np.array(\n [\n [1, 0, -s(self.theta)],\n [0, c(self.phi), c(self.theta)*s(self.phi)],\n [0, -s(self.phi), c(self.theta)*c(self.phi)]\n ]\n )\n\n self.acceleration = np.zeros((3, 1))\n\n self.sensors = []\n self.body = None\n\n # Death\n self.enable_death = enable_death\n\n def __reset__(self):\n \"\"\"Call this function to reset the simulation. This is called in function method\"\"\"\n # Position\n self.x, self.y, self.z = 0, 0, 0.5\n\n # Roll Pitch Yaw\n self.phi, self.theta, self.psi = 0, 0, 0\n\n # Linear velocities\n self.vx, self.vy, self.vz = 0, 0, 0\n\n # Angular Velocities\n self.p, self.q, self.r = 0, 0, 0\n\n print(\"LOG: The Drone is dead. Reset Simulation\")\n \n def step(self, velocities):\n \"\"\"Function to step, i.e. set the angular velocties, to be called externally by the user\"\"\"\n\n self.w1, self.w2, self.w3, self.w4 = velocities[0], -velocities[1], velocities[2], -velocities[3]\n # Decide on this, whether, you need to update as soon as you step or not\n self.update()\n\n if self.enable_death:\n self.death()\n\n # All State Update functions\n def __update_transformations__(self):\n self.R_phi = np.array(\n [\n [c(self.phi), -s(self.phi), 0],\n [s(self.phi), c(self.phi), 0],\n [0, 0, 1]\n ]\n )\n\n self.R_theta = np.array(\n [\n [1, 0, 0],\n [0, c(self.theta), -s(self.theta)],\n [0, s(self.theta), c(self.theta)]\n ]\n )\n\n self.R_psi = np.array(\n [\n [c(self.psi), -s(self.psi), 0],\n [s(self.psi), c(self.psi), 0],\n [0, 0, 1]\n ]\n )\n\n self.R = self.R_phi @ self.R_theta @ self.R_psi\n \n self.W =np.array(\n [\n [1, 0, -s(self.theta)],\n [0, c(self.phi), c(self.theta)*s(self.phi)],\n [0, -s(self.phi), c(self.theta)*c(self.phi)]\n ]\n )\n\n def __update_thrust_and_torque__(self):\n self.thrust = np.array(\n [\n [0],\n [0],\n [K*(self.w1**2 + self.w2**2 + self.w3**2 + self.w4**2)]\n ])\n\n # Torque Vector\n self.torque = np.array(\n [\n [L*K*(self.w1**2 - self.w3**2)],\n [L*K*(self.w2**2 - self.w4**2)],\n [B*(self.w1**2 - self.w2**2 + self.w3**2 - self.w4**2)]\n ]\n )\n\n # Drag Force Vector\n self.fd = -self.drag @ self.linear_velocity()\n\n def __update_acceleration__(self):\n \"\"\"Uses the omegas to update acceleration\"\"\"\n self.acceleration = self.gravity + (1/MASS)*self.R@self.thrust + (1/MASS)*self.fd\n\n def __update_omega_dot__(self):\n \"\"\"Updates omega_dot to calculate final state vector\"\"\"\n ang_vel = self.angular_velocity()\n cross_pdt = np.cross(ang_vel.reshape(3,), (self.inertia@ang_vel).reshape(3,)).reshape(3, 1)\n MM = self.torque - cross_pdt\n\n w_dot = np.linalg.inv(self.inertia)@MM\n \n self.p = w_dot[0][0]\n self.q = w_dot[1][0]\n self.r = w_dot[2][0]\n \n def update(self):\n \"\"\"This function is called everytime to update the state of the system\"\"\"\n # At this point, we assume that the angular velocities are set and hence we go on to update\n # simulation step. This will finally be updated as a gym environment, hence we can easily call the \n # functions defined in the gym environment to update the velocities.\n self.__update_transformations__()\n self.__update_thrust_and_torque__()\n self.__update_acceleration__()\n self.__update_omega_dot__()\n\n angle = self.angular_position() + self.angular_velocity() * DT\n\n # Set the angles\n self.phi = self.normalise_theta(angle[0][0])\n self.theta = self.normalise_theta(angle[1][0])\n self.psi = self.normalise_theta(angle[2][0])\n\n vel = self.linear_velocity() + self.acceleration * DT\n\n # set the velocities\n self.vx = vel[0][0]\n self.vy = vel[1][0]\n self.vz = vel[2][0]\n\n position = self.linear_position() + self.linear_velocity() * DT\n\n # set the positions\n self.x = position[0][0]\n self.y = position[1][0]\n self.z = position[2][0]\n\n #!--- Helper functions ---!\n def normalise_theta(self, angle):\n \"\"\"This is used normalise the angle within -pi to pi\"\"\"\n if angle > np.pi:\n while angle > np.pi:\n angle -= 2*np.pi\n return angle\n elif angle < -np.pi:\n while angle < np.pi:\n angle += 2*np.pi\n return angle\n return angle\n\n #!--- Attaching Sensors ---!\n def attach_sensor(self, sensor):\n \"\"\"This is called when a sensor is added to the drone\"\"\"\n self.sensors.append(sensor)\n \n def list_sensors(self):\n \"\"\"Can be used to list the sensors placed on the drone\"\"\"\n for sensor in self.sensors:\n print(sensor.__class__.__name__)\n\n #!--- Attach Body ---!\n def attach_body(self, body):\n \"\"\"This is called to attach a body to the drone, i.e. use this to visualise the drone\"\"\"\n self.body = body\n\n #!--- Death Constraints ---#\n def death(self):\n \"\"\"This function is used to terminate the simulation. This can be enabled or disabled in the constuctor\n If a death condition is reached, the simulation is reset.\"\"\"\n \n # Condition 1: If the roll or pitch is more than 60 degrees, we reset the simulation\n if abs(self.phi) > np.radians(60.0) or abs(self.theta) > np.radians(60):\n self.__reset__()\n\n # Condition 2: If the z altitude goes negative, we reset the simulation\n if self.z < 0:\n self.__reset__()","repo_name":"SuhrudhSarathy/drone_sim","sub_path":"drone_sim/sim/drone.py","file_name":"drone.py","file_ext":"py","file_size_in_byte":8439,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"85"} +{"seq_id":"20018038022","text":"from random import random\nimport numpy as np\n\n\nclass Hamming:\n \"\"\"The class that contains all functionality for encoding, \n decoding, and error correcting a random message of any given lenth\"\"\"\n\n def __init__(self, size, errPercent = 0.5):\n \"\"\"Init:\n Params:\n size: int - The size of the message the user wants to create\n errPercent: float(0-1) - The percentage chance that there will be an error in the created message\"\"\"\n # Class variables:\n self.dataBits = size\n self.errPercent = errPercent\n self.msg = []\n # Create random message of length size\n self.createMsg()\n \n # Calculate the number of parity and data bits required\n self.parityBits = self.getParityBits()\n # Total number of bits in the encoded message\n self.totalBits = 2 ** self.parityBits - 1\n\n # The code generator matrix for the hamming code\n self.G = self.createGen()\n # The parity check matrix for the hamming code\n self.H = self.createCheck()\n #Encode the message\n self.encoded = self.encode()\n # Set a random error in the message based on % chance there is one\n self.errorEncoded = []\n self.setError()\n # Select what row is required from the parity check matrix\n self.P = []\n self.getErrLocation()\n # Correct the matrix, this runs no matter what, but will return the same matrix if there is no error\n self.corrected = []\n self.correctError()\n # Create decoding matrix\n self.R = []\n self.createRecv()\n # Decode the message\n self.decoded = self.decode()\n\n def getParityBits(self):\n \"\"\"Gets the number of parity bits, and sets the number of data bits\"\"\"\n n = 0\n count = 1\n while n - self.dataBits <= count:\n count += 1\n n = pow(2, count)\n self.dataBits = n - count - 1\n return count\n\n def createGen(self):\n \"\"\"Creates the generator matrix for the Hamming code\"\"\"\n G = np.zeros((self.totalBits - self.parityBits, self.totalBits), dtype=np.uint) # k x n\n\n paritySet = set([2 ** i - 1 for i in range(self.parityBits)])\n dataSet = set(range(self.totalBits)) - paritySet\n\n # fills in parity bit columns of the generator matrix\n for par in paritySet:\n for i, data in enumerate(dataSet):\n if (par + 1) & (data + 1) != 0:\n G[i][par] = 1\n\n # fills in data bit columns of the generator matrix\n for i, data in enumerate(dataSet):\n G[i][data] = 1\n\n return G\n\n def createCheck(self):\n \"\"\"Creates the parity check matrix for the Hamming code\"\"\"\n paritySet = set([2 ** i - 1 for i in range(self.parityBits)])\n dataSet = set(range(self.totalBits)) - paritySet\n #n = total r = parity\n H = np.zeros((self.totalBits, self.parityBits), dtype=np.uint) # n x r\n\n # filling in parity bit rows of the parity check matrix\n for data in dataSet:\n for i in range(self.parityBits):\n H[data, i] = int(((data + 1) >> i) & 1)\n \n # filling in data bit rows of the parity check matrix\n for i, par in enumerate(paritySet):\n H[par][i] = 1 \n return H\n\n def setError(self):\n \"\"\"If the random number is greater than the chance, set a random error in the message\"\"\"\n chance = random()\n self.errorEncoded = self.encode()\n if chance > 1 - self.errPercent:\n spot = int((random() * 100) % len(self.errorEncoded))\n self.errorEncoded[spot] = (self.errorEncoded[spot] + 1) % 2\n \n\n def createMsg(self):\n \"\"\"Creates a message of declared length\"\"\"\n for _ in range(self.dataBits):\n # Add a random bit to each point in the msg. This creates the original message based off a size\n rnd = random()\n self.msg.append(int((rnd * 100) % 2))\n\n def encode(self):\n \"\"\"Encodes the message using the code generator matrix G\"\"\"\n while len(self.msg) < self.dataBits:\n self.msg.append(0)\n return np.dot(self.msg, self.G) % 2\n\n def getRow(self, row):\n \"\"\"Searches for a row in the parity-check matrix and returns its index.\n Returns -1 if not found.\"\"\"\n try:\n i = np.where(np.all(self.H == row, axis=1))[0][0]\n self.P = self.H[i]\n return np.where(np.all(self.H == row, axis=1))[0][0]\n except IndexError:\n return -1\n\n def getErrLocation(self):\n \"\"\"Returns the location of an error\n Returns -1 if there is no error\"\"\"\n return self.getRow(np.dot(self.errorEncoded, self.H) % 2)\n \n def correctError(self):\n \"\"\"Grabs the location of the error. If there is an error, it flips the bit at the found location\"\"\"\n errLoc = self.getErrLocation()\n ar = np.array(self.errorEncoded)\n if errLoc:\n ar[errLoc] = (ar[errLoc] + 1) % 2\n self.corrected = ar\n\n def createRecv(self):\n \"\"\"Creates the decoding matrix for the Hamming code\"\"\"\n G = np.zeros((self.totalBits - self.parityBits, self.totalBits), dtype=np.uint) # k x n\n P = [2 ** i - 1 for i in range(self.parityBits)]\n ran = 0\n # Loop through all rows\n for i in range(len(G)):\n # Loop through all columns\n for j in range(len(G[0])):\n # If j is greater than where the previous loop got to, keep going\n if j > ran:\n # Makes sure the column isn't a parity column\n if j not in P:\n G[i][j] = 1\n ran = j\n break \n # Return the transpose of the matrix for formatting purposes \n self.R = G.transpose()\n\n def decode(self):\n \"\"\"Decodes the matrix using the R matrix and returns the original message\"\"\"\n return np.dot(self.corrected, self.R) \n \n\n\n def print(self):\n \"\"\"Helper function for pretty formatting\"\"\"\n print(\"Message : \" + str(np.array(self.msg)))\n print(\"Send Vector : \" + str(self.encoded))\n print(\"Recieved Message : \" + str(self.errorEncoded))\n print(\"Parity Check : \" + str(self.P))\n print(\"Corrected Message: \" + str(self.corrected))\n print(\"Decoded Message : \" + str(self.decoded))\n \n\n\ndef getInput():\n \"\"\"Gets the user's input for number of data bits in the message\"\"\"\n return input(\"Enter number of databits: \")\n\n\nif __name__ == \"__main__\":\n inp = 0\n # Loop to make sure the input is an integer\n while True:\n try:\n inp = int(getInput())\n break\n except ValueError:\n print(\"Please ensure input is an integer!\")\n continue\n # Create the hamming object, and all the requred information about it\n ham = Hamming(inp, errPercent = 0.0)\n ham.print()\n\n","repo_name":"WeissTMark/Org-and-Arch","sub_path":"Hamming code/Hamming.py","file_name":"Hamming.py","file_ext":"py","file_size_in_byte":7072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15174106604","text":"class IniClient(Client):\n\n def __init__(self, iceOptions, iceProfile=None, *args, **kargs):\n Client.__init__(self, *args, **kargs)\n self.iceOptions = iceOptions\n self.iceProfile = iceProfile\n\n def setup(self, current):\n if self.iceProfile:\n current.createFile(\"ice.profiles\", [\n \"[%s]\" % self.iceProfile,\n \"ice.config=\\\"config.client\\\"\",\n \"ice.options=\\\"%s\\\"\" % self.iceOptions,\n ])\n current.write(\"testing... \")\n\n def teardown(self, current, success):\n if success:\n current.writeln(\"ok\")\n\n def getPhpArgs(self, current):\n if self.iceProfile:\n return [\"-d\", \"ice.profiles=\\\"ice.profiles\\\"\"]\n else:\n return [\"-d\", \"ice.options=\\\"{0}\\\"\".format(self.iceOptions), \"-d\", \"ice.config=\\\"config.client\\\"\"]\n\nTestSuite(__name__, [\n ClientTestCase(\"php INI settings\",\n client=IniClient(\"--Ice.Trace.Network=1 --Ice.Warn.Connections=1\")),\n ClientTestCase(\"php INI settings with profiles\",\n client=IniClient(\"--Ice.Trace.Network=1 --Ice.Warn.Connections=1\",\n \"Test\",\n exe=\"ClientWithProfile\"))\n])\n","repo_name":"zeroc-ice/ice","sub_path":"php/test/Ice/ini/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":1942,"dataset":"github-code","pt":"85"} +{"seq_id":"5327835044","text":"from gem.model import *\n\nclass Model(GemModel):\n \"\"\"\n Model description\n \"\"\"\n meta={\n #\n # Metadata\n #\n 'name': 'forecast',\n 'author': 'Koko Alberti',\n 'contact': 'kokoalberti@fastmail.nl',\n 'abstract': 'Cellular automata model which uses GFS forecasts',\n 'license': 'All Rights Reserved',\n 'tags': ['demo','fire','forest fire','forecast','cellular automata'],\n 'discretization': 'southeast_african_countries_10000m',\n 'maxchunks': 1\n }\n parameters={\n #\n # These are default params that will be overwritten by params\n # specified in the web application\n #\n 'fire_hazard_level': 3\n }\n time={\n #\n # Defines the time component of the model. \n #\n 'start': 'now', #defaults to now if this string can't be parsed as a utc datetime\n 'startroundoff': -21600, #round down to the nearest 6h, defaults to 60 seconds\n 'startoffset': 0, #and go back three days, defaults to 0\n 'timesteps': 16,\n 'timesteplength': 10800 \n }\n datasources={\n #\n # Datasources are WCS servers with coverages. They are queried\n # upon initialization and their layer names stored internally. The\n # layers names can be accessed via self.readmap() and\n # the system will then read the map from the correct WCS server.\n #\n 'wcs':[\n 'http://turbo.geo.uu.nl/cgi-bin/mapserv?MAP=/data/projectdata/globaldata/globaldata.map' \n ],\n 'gfs': {\n 'option':'value'\n }\n }\n reporting={\n #\n # The reporting section adds metadata to model output attributes.\n # By reporting a map with self.report() and the name matches\n # keys listed below, that information will be used in the webmap.\n # If you report maps without defining them here it will not show\n # up in the web interface.\n #\n 'temp': {\n 'title': \"Temperature\",\n 'units': \"C\",\n 'info': \"Forecast temperature in degrees Celcius.\",\n 'datatype': \"Float32\",\n 'symbolizer':{\n 'type': \"pseudocolor\",\n 'clamp': True,\n 'ticks': 5, #ticks only works on pseudocolor symbolizers\n 'colors': [\"#7e1e9c\",\"#0343df\",\"#15b01a\",\"#fac205\",\"#fd3c06\",\"#e50000\",\"#840000\"],\n 'values': [-10,50.0],\n 'labels': []\n }\n },\n 'grade': {\n 'title': \"Slope\",\n 'units': \"m/m\",\n 'info': \"Grade of the slope expressed in meters elevation per meter distance.\",\n 'datatype': \"Float32\",\n 'symbolizer':{\n 'type': \"pseudocolor\",\n 'clamp': True,\n 'ticks': 5, #ticks only works on pseudocolor symbolizers\n 'colors': [\"#006600\",\"#FFCC00\",\"#CC0000\",\"#4A0000\"],\n 'values': [0.0,1.5],\n 'labels': []\n }\n }\n }\n def initial(self):\n #self.dem=self.readmap('srtm.elevation')\n #self.modis=self.readmap('modis.ndvi.2012.002')\n \n \n #self.grade=slope(self.dem)\n pass\n \n\n def dynamic(self):\n self.status()\n #self.grade = slope(self.dem)\n #self.report(self.grade,\"grade\")\n self.temp=self.readmap('Temperature_surface')\n self.temp=self.temp-273.15 #convert kelvin to celcius\n self.report(self.temp,\"temp\")\n\n def postdynamic(self):\n logger.debug(\"Hello postdynamic!\")\n\n \n\n","repo_name":"pcraster/gems","sub_path":"data/models/forecast/forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10920979975","text":"from algorithm.li.extract.utils.dbutils import dbs\n\n\ndef paper_seg():\n import re\n import jieba\n jieba.load_userdict('.\\\\dicts\\\\user_dict_1.txt')\n term_dict = {}.fromkeys(open('.\\\\dicts\\\\term.txt', 'r', encoding='utf8').read().split('\\n'), 'ok')\n\n # s_sql = \"SELECT id, title, abstract FROM paper_data WHERE discipline='0812'\"\n s_sql = \"SELECT id, title, abstract FROM paper_data WHERE id in (632158,632690,633512,634259,634504,644862,645697,647947,651835,696197,697667,698942,701609,701882,702953,703279,719978,778166,781868,782636,785997,787785,788662,788852,789241,868144,869130,869391,869971,870955,871869,873702,877593,878509,878761,1057022,1069453,1070486,1085083,1085705,1086615,1088270,1096989,1328935,1329754,1330950,1333472,1336010,1376006,1379811,1382522,1384484,1519331,1538164,1591831,1912371,1913089,1913270,1915550,1916681,1921026,1921611,1922188,1923005,1923339,1923498,1924501,1925167,1934011,1935109,1942329,1947322,1951950,1955110,1978880,1983142,1986760,1987129,1989538,1990521,1991737,1995202,2023057,2030104,2032255,2032605,2039093,2043059,2045712,2051244,2064811,2090132,2090809,2091235,2102585,2103888)\"\n data_list = dbs.getDics(s_sql)\n\n u_sql = \"UPDATE paper_data SET word_seg=%s WHERE id=%s\"\n u_list = []\n\n fields_dict = dict()\n\n for data in data_list:\n title = data['title']\n abstract = data['abstract']\n\n word_list = jieba.cut(title+\"\\n\"+abstract, HMM=False, cut_all=True)\n seg_dict = dict()\n\n for word in word_list:\n if term_dict.get(word, \"\") != \"\":\n c = seg_dict.get(word, 0)\n seg_dict[word] = c+1\n\n cc = fields_dict.get(word, 0)\n fields_dict[word] = cc+1\n\n # u_list.append((str(seg_dict), data['id']))\n print(abstract)\n print((str(seg_dict), data['id']))\n print(\"*\" * 10)\n\n for w, k in fields_dict.items():\n print(\"%s,%s\\n\" % (w, str(k)))\n\n # l = len(u_list)\n # if l == 10000:\n # print(dbs.exe_many(u_sql, u_list))\n # u_list = []\n\n # print(len(u_list))\n # print(dbs.exe_many(u_sql, u_list))\n\n pass\n\n\ndef get_user_dict():\n term_list = open('.\\\\dicts\\\\term.txt', 'r', encoding='utf8').read().split('\\n')\n r_list = [term+\" \"+str(10**len(term))+\" \"+\"n\" for term in term_list]\n fw = open('.\\\\dicts\\\\user_dict_1.txt', 'w', encoding='utf8')\n fw.write('\\n'.join(r_list))\n fw.close()\n pass\n\n\ndef check_word():\n import re\n\n s_sql = \"SELECT id, title, abstract FROM paper_data WHERE discipline='0812'\"\n data_list = dbs.getDics(s_sql)\n\n for data in data_list:\n title = data['title']\n # abstract = data['abstract']\n abstract = \"\"\n if re.findall(r'半监督', title + abstract):\n print(data['id'])\n print(title + abstract)\n if re.findall(r'k近邻|K近邻', title + abstract):\n print(data['id'])\n print(title + abstract)\n if re.findall(r'k值|K值', title + abstract):\n print(data['id'])\n print(title + abstract)\n if re.findall(r'CNN|cnn', title + abstract):\n print(data['id'])\n print(title + abstract)\n\n\ndef test():\n t_list = open('.\\\\test\\\\ttt.txt', 'r', encoding='utf8').read().split('\\n')\n t_dict = dict()\n for t in t_list:\n the_t = t.split(',')\n r = the_t[0]\n f = the_t[1]\n\n c = t_dict.get(r, 0)\n t_dict[r] = c+int(f)\n\n for w, v in t_dict.items():\n print(\"%s,%s\" % (w, str(v)))\n\n print(len(t_list))\n print(len(t_dict))\n\n\ndef t():\n import jieba.posseg as pseg\n import xlwt\n\n s_sql = \"SELECT id, title, abstract FROM paper_data WHERE discipline='0812'\"\n data_list = dbs.getDics(s_sql)\n\n flag_list = ['vd', 'g', 'h', 'f', 's', 'r', 'nt', 'm', 'ad', 'ns', 'zg', 'z', 'ag', 'q', 'yg', 'd', 'u', 'ul', 'j', 'a', 'y', 'ug', 'vg', 't', 'p', 'mq', 'uj', 'o', 'uv', 'k', 'c', 'nz', 'nrfg', 'tg', 'i']\n\n word_dict = dict()\n x_word_dict = dict()\n for data in data_list:\n title = data['title']\n abstract = data['abstract']\n\n word_list = pseg.cut(title + \"\\n\" + abstract, HMM=True)\n for w, f in word_list:\n if f in flag_list:\n key = w+\"--SPLIT--\"+f\n c = word_dict.get(key, 0)\n word_dict[key] = c+1\n elif f == \"x\":\n key = w+\"--SPLIT--\"+f\n c = x_word_dict.get(key, 0)\n x_word_dict[key] = c+1\n pass\n\n wbk = xlwt.Workbook(encoding='utf-8')\n sheet = wbk.add_sheet('sheet1')\n row = 0\n for k, v in word_dict.items():\n word = k.split('--SPLIT--')[0]\n flag = k.split('--SPLIT--')[1]\n f = v\n sheet.write(row, 0, word)\n sheet.write(row, 1, flag)\n sheet.write(row, 2, f)\n row += 1\n\n wbk.save('.\\\\test\\\\con_stop.xls')\n print(row)\n\n\ndef x_t():\n import jieba.posseg as pseg\n\n s_sql = \"SELECT id, title, abstract FROM paper_data WHERE discipline='0812'\"\n data_list = dbs.getDics(s_sql)\n\n x_word_dict = dict()\n for data in data_list:\n title = data['title']\n abstract = data['abstract']\n\n word_list = pseg.cut(title + \"\\n\" + abstract, HMM=True)\n for w, f in word_list:\n if f == \"x\":\n key = w+\"--SPLIT--\"+f\n c = x_word_dict.get(key, 0)\n x_word_dict[key] = c+1\n pass\n\n fw = open('.\\\\stopword_base.txt', 'w', encoding='utf8')\n\n save_list = [\"A\", \"B\", \"C\", \"D\", \"E\"]\n\n for k, v in x_word_dict.items():\n word = k.split('--SPLIT--')[0]\n flag = k.split('--SPLIT--')[1]\n f = v\n\n\nif __name__ == \"__main__\":\n # get_user_dict()\n # paper_seg()\n # test()\n t()\n pass\n","repo_name":"fengges/eds","sub_path":"algorithm/li/extract/fields_extract.py","file_name":"fields_extract.py","file_ext":"py","file_size_in_byte":5797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42280375897","text":"import numpy as np\nimport pandas as pd\nimport cv2\nimport os\nimport shutil\n\nfrom sklearn.model_selection import train_test_split\n\nclass Dataset:\n def __init__(self, path_metadata: str, path_dataset: str, n_data: int, test_size: float, valid_size: float) -> None:\n \"\"\"\n :param path_metadata: path to csv with image paths and respective classes\n :param path_dataset: path leading to dataset entrance to connect with metadata (path)\n :param test_size: testing dataset size in data split\n :param valid_size: validation dataset in data split\n \"\"\"\n self.metadata = path_metadata\n self.path_dataset = path_dataset\n self.n_data = n_data\n self.test_size = test_size\n self.valid_size = valid_size\n\n def to_path(self, test_seed=1, val_seed=1, test_size=0.2, valid_size=0.1) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n print(\"Splitting dataset into train/valid/test.\")\n df = pd.read_csv(self.metadata)\n\n train: pd.DataFrame\n valid: pd.DataFrame\n test: pd.DataFrame\n\n train_and_valid, test = train_test_split(df, test_size=test_size, random_state=test_seed)\n train, valid = train_test_split(train_and_valid, test_size=valid_size, random_state=val_seed)\n\n print('here-test', test_size)\n print('here-valid', valid_size)\n\n del train[\"Unnamed: 0\"]\n del test[\"Unnamed: 0\"]\n del valid[\"Unnamed: 0\"] \n\n return train, test, valid\n\n\n def to_pixel(self, test_seed=1, val_seed=1, test_size=0.2, valid_size=0.1, batch=(0, None), target_size=(256, 256)) -> tuple[list[np.ndarray], list[np.ndarray]]:\n print(\"Converting path dataset to images.\")\n data = self.to_path(test_seed=test_seed, val_seed=val_seed, test_size=test_size, valid_size=valid_size)\n\n data_x: list[np.ndarray] = []\n data_y: list[np.ndarray] = []\n\n info = [\"valid\", \"test\", \"train\"]\n for x_m in data:\n print(\"Collecting data for: \", info.pop())\n # runs 3 times for train, test and validation\n if None in batch:\n n_data = x_m.shape[0]\n init = 0\n else:\n n_data = batch[1]\n init = batch[0]\n\n channels = 3\n x_p = np.zeros([n_data, target_size[0], target_size[1], channels], dtype=np.uint8)\n y = np.zeros([n_data], dtype=np.uint8)\n i = init\n while i < init + n_data:\n matrix = cv2.imread(x_m[\"filename\"].iloc[i])\n # 3 channels\n for c in range(channels):\n x_p[i-init, :, :, c] = cv2.resize(matrix[:, :, c], target_size)\n\n y[i-init] = x_m[list(x_m.columns)[-1]].iloc[i]\n\n i += 1\n\n data_x.append(x_p)\n data_y.append(y)\n\n # data[0] for x\n # data[1] for y\n # data[i][j] for train, test and validation\n return data_x, data_y\n\n def to_folders(self, test_seed=1, val_seed=1, test_size=0.2, valid_size=0.1) -> None:\n data = self.to_path(test_seed=test_seed, val_seed=val_seed, test_size=test_size, valid_size=valid_size)\n\n print('Recreating the structure of the dataset ...')\n parent_dir = '../tests/resources/'\n directory = 'new_dataset'\n new_path = os.path.join(parent_dir, directory)\n\n try:\n shutil.rmtree(new_path)\n except FileNotFoundError:\n pass\n\n # Create the new directory\n os.mkdir(new_path)\n\n df_list = ['valid', 'test', 'train']\n df_list_2 = df_list.copy()\n for df in data: # train, test, valid\n folder_name = df_list.pop()\n os.mkdir(os.path.join(new_path, folder_name))\n for i in df.iloc[:, -1].unique():\n os.mkdir(os.path.join(new_path, folder_name, str(i)))\n\n # Move images to new directory\n for df in data:\n folder_name_2 = df_list_2.pop()\n for index, row in df.iterrows():\n src = row['filename']\n dst = os.path.join(new_path, folder_name_2, str(row.iloc[-1]), os.path.basename(src))\n shutil.copyfile(src, dst)\n \n return new_path\n","repo_name":"AnaMiguelRodrigues1/autolens","sub_path":"autolens/dataset/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34081842315","text":"import face_recognition as fr\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport datetime as dt\nimport os\nimport keyboard\n\nif not os.path.exists('Security Logs'):\n os.mkdir('Security Logs')\n\n# Store all known names and known faces\nknown_faces_dir = 'known_faces'\nknown_faces = []\nknown_names = []\n\nfor name in os.listdir(known_faces_dir): # iterate through each file in the known_faces\n for filename in os.listdir(f'{known_faces_dir}/{name}'): # iterate through files in a known name\n image = fr.load_image_file(f'{known_faces_dir}/{name}/{filename}')\n encoding = fr.face_encodings(image)[0] # list of lists, want first entry\n known_faces.append(encoding)\n known_names.append(name)\n\n# keep_indices = pd.DataFrame(data=known_names).T\n# keep_indices.columns = known_names\ncolumns = ['Name', 'Time of Entry', 'Left at']\nindices = range(0, 1, 1)\nsecurity_log = pd.DataFrame(index=indices, columns=columns)\ntest = pd.DataFrame(data={'Name': ['Harman'], 'Time of Entry': [0], 'Left at': [0]})\nsecurity_log = security_log.append(test)\nsecurity_log = security_log.reset_index(drop=True)\n\ninstance = dt.datetime.now()\ntoday = instance.date().strftime(\"%Y-%m-%d\")\nprev_frame_occupants = set()\n\nvideo = cv2.VideoCapture(0) # take video from webcam\nrecord = True\nif not os.path.exists(f'Security Logs/{today}'):\n os.mkdir(f'Security Logs/{today}')\n\nwhile not (keyboard.is_pressed('q')):\n ret, frame = video.read()\n color_corrected = frame[:, :, ::-1]\n face_locations = fr.face_locations(color_corrected, model='cnn') # using hog by default because faster\n face_encodings = fr.face_encodings(color_corrected, face_locations)\n time = instance.time().strftime(\"%H:%M:%S\")\n current_occupants = set() # don't know who is currently in the room yet\n for face_location, face_encoding in zip(face_locations, face_encodings): # get current occupants\n matches = fr.compare_faces(known_faces, face_encoding) # list of boolean variables\n disparity = fr.face_distance(known_faces, face_encoding)\n best_match_index = np.argmin(disparity)\n name = 'Unrecognized'\n if matches[best_match_index]: # recognized a face, room initially empty\n name = known_names[best_match_index]\n current_occupants.add(name)\n top = face_location[0]\n right = face_location[1]\n bottom = face_location[2]\n left = face_location[3]\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n entered = current_occupants.difference(prev_frame_occupants) # who entered the room\n for name in entered:\n security_log = security_log.append(pd.DataFrame(data={'Name': [name], 'Time of Entry': [time], 'Left at': [0]}))\n security_log = security_log.reset_index(drop=True)\n left = prev_frame_occupants.difference(current_occupants) # who left the room\n for name in left:\n index = security_log.loc[(security_log['Name'] == name) & (security_log['Left at'] == 0)].index.to_list()[0]\n security_log.loc[index, ['Left at']] = time\n prev_frame_occupants = current_occupants\n\n cv2.imshow('Surveillance', frame)\n if cv2.waitKey(1) and 0xFF == ord('q'):\n break\n\nvideo.release()\ncv2.destroyAllWindows()\nsecurity_log.to_csv(f'Security Logs/{today}.csv')\n\n","repo_name":"khunguraharman/Security-Surveillance-with-Face-Recognition","sub_path":"SecurityScript.py","file_name":"SecurityScript.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"70234909077","text":"#!/usr/bin/env python3\n\"\"\" 0x00-linear_algebra Task 5 \"\"\"\n\n\ndef add_matrices2D(mat1, mat2):\n \"\"\" adds two matrices element-wise\"\"\"\n if len(mat1) != len(mat2) or len(mat1[0]) != len(mat2[0]):\n return None\n return [[mat1[i][j] + mat2[i][j]\n for j, _ in enumerate(mat1[0])]\n for i, _ in enumerate(mat1)]\n","repo_name":"leocjj/holbertonschool-machine_learning","sub_path":"math/0x00-linear_algebra/5-across_the_planes.py","file_name":"5-across_the_planes.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"27699636994","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n ha=headA;hb=headB\n while ha and hb:\n ha=ha.next;hb=hb.next\n if not ha:\n ha,hb=hb,ha\n headA,headB=headB,headA\n diff=0\n while ha:\n diff+=1\n ha=ha.next\n ha=headA;hb=headB\n while diff>0:\n ha=ha.next\n diff-=1\n while ha:\n if ha==hb:\n return ha\n ha=ha.next;hb=hb.next\n return None\n","repo_name":"sigmeta/Leetcode","sub_path":"101-200/160.py","file_name":"160.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20968081467","text":"import argparse\nimport os\nimport glob\nimport numpy as np\nimport re\n\ndef get_single_exp_status(fname):\n record = []\n with open(fname) as f:\n data = f.read().splitlines()\n for i in range(len(data)):\n if not i & 0x1:\n continue\n # cnt = re.findall('-?\\d+.?\\d+', data[i])\n cnt = float(data[i].split(' ')[3])\n record.append(cnt)\n return record\n \n\ndef generate_report(in_directory, out_directory):\n d = dict()\n for path in glob.glob(os.path.join(in_directory,\"*.txt\")):\n fname = os.path.split(path)[-1][:-4]\n d[fname] = get_single_exp_status(path)\n \n for key, value in d.items():\n # print(value)\n print(key, \"%.3f\" % np.mean(value), \"%.3f\" % np.std(value))\n \n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-i','--in_directory', type = str, default='./report', help='Directory to get input files')\n parser.add_argument('-o','--out_directory', type = str, default='./report', help='Directory to save output reports')\n args = parser.parse_args()\n \n generate_report(args.in_directory, args.out_directory)","repo_name":"Nina-yang/maxpool-add","sub_path":"generate_report.py","file_name":"generate_report.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9682452697","text":"import os\nimport ssl\nimport argparse\nimport requests\nimport urllib.request\nfrom bs4 import BeautifulSoup\n\nparser = argparse.ArgumentParser(\n prog='PYQ Downloaer',\n description='Downloads PYQs from the BSW Website for a particular course',)\nparser.add_argument('-c', '--course', type=str, required=True, dest=\"course\", default=None)\nparser.add_argument(\"-p\", '--path', type=str, required=False, dest=\"path\", default=\"./\")\nargs = parser.parse_args() \ncourse = args.course\nprint(course)\npath = args.path\n\nurl = f\"https://bsw.iitd.ac.in/coursepage.php?course={course}\"\n\n\ndef get_all_courses():\n soup = BeautifulSoup(requests.get(\"https://bsw.iitd.ac.in/question_papers.php\", verify=False).text, \"html.parser\")\n courses = [link.get_text() for link in soup.find_all(\"a\", class_=\"list-group-item\")]\n return courses\n\ndef check_valid_course(course):\n return course in get_all_courses()\n\n\nif not check_valid_course(course):\n print(\"Invalid Course\")\n exit()\n \n\nsoup = BeautifulSoup(requests.get(url, verify=False).text, \"html.parser\")\n\nresources = soup.find_all(\"a\", class_=\"list-group-item\")\n\nssl_context = ssl.create_default_context()\nssl_context.check_hostname = False\nssl_context.verify_mode = ssl.CERT_NONE\nhttps_handler = urllib.request.HTTPSHandler(context=ssl_context)\nopener = urllib.request.build_opener(https_handler)\nurllib.request.install_opener(opener)\n\n\ntry:\n os.makedirs(os.path.join(path, course))\nexcept OSError as e:\n print(f\"Error creating folder: {e}\")\n exit()\n\nfor resource in resources:\n resource_url = f\"https://bsw.iitd.ac.in/{resource.get('href')}\"\n semester = resource.get_text()\n exam_type = resource_url.split(\"/\")[-2]\n os.makedirs(os.path.join(path, course, semester), exist_ok=True)\n local_file_path = os.path.join(path, course, semester, resource_url.split(\"/\")[-1])\n urllib.request.urlretrieve(resource_url, local_file_path)","repo_name":"ChinmayMittal/IITD-SCRIPTS","sub_path":"PyqDownloader/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21564971043","text":"# 13 / 15 통과\n\ndef solution(genres, plays):\n\n answer = []\n\n # 딕셔너리를 만들어서 해당 장르별로 가장 많은 재생횟수 별로 sort된 장르 리스트 생성\n total = {}\n for i in range(len(genres)):\n if genres[i] in total:\n total[genres[i]] += plays[i]\n else:\n total[genres[i]] = plays[i]\n\n total = sorted(total.items(), key=lambda x: x[1], reverse=True)\n\n # 장르와 플레이를 2중 리스트로 각각 묶기 ([재생횟수, 장르, idx])\n temp = list(zip(plays, genres, range(len(genres))))\n\n # 2중 리스트 재생횟수 별로 sort\n rough = sorted(temp, reverse=True)\n # print(rough)\n # print(total)\n\n # sort된 장르 리스트 순서로 2중 리스트를 돌며 answer에 할당\n for k in total:\n cnt = 0\n for candidate in rough:\n if cnt == 2:\n break\n if candidate[1] == k[0]:\n cnt += 1\n answer.append(candidate[2])\n # print(answer)\n return answer\n","repo_name":"SPlCYWOLF/algorithm-practices","sub_path":"python/programmers/220103/베스트앨범/s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33485364243","text":"import json\nfrom django.http import JsonResponse\nfrom django.middleware.csrf import get_token\nfrom django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.views.decorators.http import require_POST\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import (\n exceptions as rest_exceptions,\n response,\n decorators as rest_decorators,\n permissions as rest_permissions,\n)\n\nfrom student.models import Student\nfrom custom.models import User\nfrom custom.api.serializers import UserSerializer\nfrom .serializers import StudentSerializer, UpdateSerializer\n\n@rest_decorators.api_view([\"GET\"])\ndef get_session_id(request):\n session_id = request.session.session_key\n return Response({'sessionId': session_id})\n\nclass getSession(APIView):\n authentication_classes = [SessionAuthentication]\n permission_classes = [IsAuthenticated]\n \n def get(request):\n #session_id = request.session.session_key\n return JsonResponse(request.session.session_key, safe=True)\n\ndef get_csrf(request):\n response = JsonResponse(\n {\"Info\": \"Success - Set CSRF cookie\", \"Token\": get_token(request)}\n )\n response[\"X-CSRFToken\"] = get_token(request)\n token = get_token(request)\n\n print(token)\n return response\n\n\n@ensure_csrf_cookie\ndef check_auth(request):\n if not request.user.is_authenticated:\n return JsonResponse({\"isAuthenticated\": False})\n\n return JsonResponse({\"isAuthenticated\": True})\n\n\n@require_POST\ndef loginView(request):\n data = json.loads(request.body)\n email = data.get(\"email\")\n password = data.get(\"password\")\n\n if email is None or password is None:\n return JsonResponse({\"Info\": \"Email and Password are needed\"})\n\n user = authenticate(email=email, password=password)\n\n if user is None:\n return JsonResponse(\n {\"Info\": \"User with given credentials does not exist\"}, status=400\n )\n\n login(request, user)\n return JsonResponse({\"Info\": \"User logged in successfully\"})\n\n\ndef logoutView(request):\n if not request.user.is_authenticated:\n return JsonResponse({\"detail\": \"You're not logged in\"}, status=400)\n\n logout(request)\n return JsonResponse({\"detail\": \"Successfully logged out\"})\n\n\nclass WhoAmIView(APIView):\n authentication_classes = [SessionAuthentication]\n permission_classes = [IsAuthenticated]\n\n @staticmethod\n def get(request, format=None):\n print(request.user.username)\n user = request.user\n data = {\n 'first_name': user.first_name,\n 'last_name': user.last_name,\n 'username': user.username,\n 'email': user.email,\n 'student_reg': user.student_reg_no,\n 'class_course': user.class_course,\n 'department': user.department,\n } \n return JsonResponse(data, safe=False)\n\n\nclass StudentOnlyView(APIView):\n permission_classes = [IsAuthenticated]\n\n def get(self, request, format=None):\n try:\n user = request.user\n user = UserSerializer(user)\n\n return Response({\"user\": user.data}, status=status.HTTP_200_OK)\n except:\n return Response(\n {\"error\": \"Something went wrong when trying to load user\"},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR,\n )\n \ndef get_user_data(request):\n user = request.user\n data = {\n 'username': user.username,\n 'email': user.email,\n # add any other user data you want to include\n }\n return JsonResponse(data) \n\n\n@rest_decorators.api_view([\"POST\"])\n@rest_decorators.permission_classes([rest_permissions.AllowAny])\n# @method_decorator(csrf_protect, name='dispatch')\ndef registerView(request):\n serializer = StudentSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n user = serializer.save()\n\n if user is not None:\n return response.Response(\n {\n \"user\": UserSerializer(user).data,\n \"message\": \"Account created successfully\",\n }\n )\n\n return rest_exceptions.AuthenticationFailed(\"Invalid credentials!\")\n\n@rest_decorators.api_view(['PUT', 'PATCH'])\n@rest_decorators.permission_classes([rest_permissions.IsAuthenticated])\ndef update_account(request):\n user = request.user\n serializer = UpdateSerializer(user, data=request.data, partial=True)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)\n\n@rest_decorators.api_view(['DELETE'])\n@rest_decorators.permission_classes([rest_permissions.IsAuthenticated])\ndef delete_account(request):\n user = request.user\n user.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n","repo_name":"mwombeki6/chief","sub_path":"student/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"30029943568","text":"# Given a sorted array of integers (not necessarily distinct) A and an integer B,\r\n# find and return how many pair of integers ( A[i], A[j] ) such that i != j have sum equal to B.\r\n# Since the number of such pairs can be very large, return number of such pairs modulo (10^9 + 7).\r\n# 1 <= |A| <= 100000\r\n# 1 <= A[i] <= 10^9\r\n# 1 <= B <= 10^9\r\ndef pairsWithGivenSum2(A, B):\r\n frequencyDict = {}\r\n N = len(A)\r\n for i in range(N):\r\n if A[i] in frequencyDict.keys():\r\n frequencyDict[A[i]] += 1\r\n else:\r\n frequencyDict[A[i]] = 1\r\n\r\n pairCount = 0\r\n\r\n for i in range(N):\r\n if B - A[i] in frequencyDict.keys():\r\n pairCount += (frequencyDict[B - A[i]]) % (10**9 + 7)\r\n if B - A[i] == A[i]:\r\n pairCount -= 1\r\n\r\n return (pairCount // 2) % (10**9 + 7)\r\n\r\n\r\nprint(pairsWithGivenSum2([1, 5, 7, -1, 5], 6)) # 3\r\nprint(pairsWithGivenSum2([1, 1, 1], 2)) # 3\r\nprint(pairsWithGivenSum2([1, 1], 2)) # 1\r\nprint(pairsWithGivenSum2([2, 3, 5, 6, 10], 6)) # 0\r\n","repo_name":"deysantanu84/python-portfolio","sub_path":"problemSolving/twoPointers/pairsWithGivenSum2.py","file_name":"pairsWithGivenSum2.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26897374086","text":"# Parallel timing class for profiling purposes\nfrom time import time\nimport mpi4py.MPI as MPI\nimport numpy as np\n\ncomm = MPI.COMM_WORLD\n\nfunclst = []\n\ncounter = []\ntimelst = []\ninittime = time()\n\ndef add(time, name):\n if name in funclst:\n idx = funclst.index(name)\n counter[idx] += 1\n timelst[idx] += time\n else:\n funclst.append(name)\n counter.append(1)\n timelst.append(time)\n\ndef finalize():\n counterlst = comm.reduce(counter, op=MPI.SUM, root=0)\n redtimelst = comm.reduce(timelst, op=MPI.SUM, root=0)\n # Output all time usage to stdout\n if comm.rank == 0:\n print('\\nSubroutine : No. of Calls: Total(s): Per Proc(s)')\n for ii in range(len(funclst)):\n print('{0:13s}: {1:10d}:{2:12d}:{3:12d}'.\\\n format(funclst[ii], counterlst[ii], \\\n int(redtimelst[ii]), int(redtimelst[ii]/comm.size) ) )\n\nclass Timer(object):\n def __init__(self, name):\n self.name = name\n self.inittime = time()\n\n def __del__(self):\n add(self.elapsed(), self.name)\n\n def elapsed(self):\n return time() - self.inittime\n","repo_name":"cggdgs/mapreduce","sub_path":"timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3386561580","text":"import numpy as np\nimport random\nimport cv2 \n\n##########################\n# \n##########################\nRENDER_MAZE = False\nmaze = None\nroom_id = 1\ndef gen_recursive(x,y,room_max,prob):\n global maze, RENDER_MAZE, room_id\n # Check Space\n if x[1]-x[0]<=1 or y[1]-y[0]<=1:\n return\n \n gen_room = np.random.rand() < prob \n if x[1]-x[0]>room_max[0] or y[1]-y[0]>room_max[1] or gen_room==False:\n # Generate Wall\n wall_v = random.randrange(x[0]+1,x[1],2)\n wall_h = random.randrange(y[0]+1,y[1],2)\n maze[y[0]:y[1]+1, wall_v] = 255\n maze[wall_h, x[0]:x[1]+1] = 255\n \n # Generate Gap\n r1 = np.random.randint(0,3)\n if r1 != 0:\n r2 = random.randrange(x[0],wall_v,2)\n maze[wall_h,r2] = 0\n if r1 != 1:\n r2 = random.randrange(wall_v+1,x[1]+1,2)\n maze[wall_h,r2] = 0\n if r1 != 2:\n r2 = random.randrange(y[0],wall_h,2)\n maze[r2,wall_v] = 0\n if r1 != 3:\n r2 = random.randrange(wall_h+1,y[1]+1,2)\n maze[r2,wall_v] = 0\n \n # Draw\n if RENDER_MAZE:\n maze_re = cv2.resize(maze, (maze.shape[1]*10, maze.shape[0]*10), interpolation=cv2.INTER_NEAREST)\n cv2.imshow(\"maze\", 255-maze_re)\n cv2.waitKey(30)\n\n # Recursive\n gen_recursive((x[0],wall_v-1),(y[0],wall_h-1),room_max,prob)\n gen_recursive((wall_v+1,x[1]),(y[0],wall_h-1),room_max,prob)\n gen_recursive((x[0],wall_v-1),(wall_h+1,y[1]),room_max,prob)\n gen_recursive((wall_v+1,x[1]),(wall_h+1,y[1]),room_max,prob)\n else:\n # Generate Room\n maze[y[0]:y[1]+1, x[0]:x[1]+1] = room_id\n room_id += 1\n\ndef gen_maze(width=15, height=15, room_max=(7,7), prob=0.8):\n global maze\n # Generate Initial Map\n maze = np.zeros([height, width], dtype=np.uint8)\n maze[:,0] = 255\n maze[0,:] = 255\n maze[:,width-1] = 255\n maze[height-1,:] = 255\n # Start Recursive\n gen_recursive((1,width-2),(1,height-2),room_max,prob)\n return maze\n\nif __name__ == \"__main__\":\n RENDER_MAZE = True\n for i in range(5):\n gen_maze(15,15,(7,7),0.8)\n print(maze)\n cv2.waitKey(0)","repo_name":"jerrywiston/Scene-Memory-Network","sub_path":"maze3d/MazeGen/maze_gen_grid.py","file_name":"maze_gen_grid.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"7260231442","text":"import os\nimport secrets\nfrom PIL import Image\nfrom flask import url_for, current_app\n\n\ndef save_picture(form_picture):\n ''' \n данная функция сохраняет аватарку пользователя в файловую систему\n в random_hex записываем случайное значение, которое будем использовать\n в качестве имени файла\n с помощью os.path.splitext получаем название загружаемого файла и \n его расширение\n в picture_fn пишем название файла, который будем сохранять\n в picture_path пишем путь по которому будем сохранять файл с новым названием\n app.root_path- полный пусть до package directory\n '''\n random_hex = secrets.token_hex(8) \n f_name, f_ext = os.path.splitext(form_picture.filename)\n picture_fn = random_hex + f_ext\n picture_path = os.path.join(current_app.root_path, 'static/profile_pics', picture_fn)\n\n # минимизируем аватарку и сохраняем\n output_size = (125, 125)\n i = Image.open(form_picture)\n i.thumbnail(output_size)\n i.save(picture_path)\n\n return picture_fn","repo_name":"RinatR/ad_and_israel","sub_path":"ad_and_israel/users/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"6091329680","text":"import os\nimport imp\nimport logging\n\n# Third party libraries\nimport numpy as np\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\n# My libraries\nimport ScopePy_panels as panel\nimport ScopePy_channel as ch\nimport ScopePy_widgets as wid\n\n#==============================================================================\n#%% Logger\n#==============================================================================\n# create logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# Add do nothing handler\nlogger.addHandler(logging.NullHandler())\n\n# create console handler and set level to debug\ncon = logging.StreamHandler()\ncon.setLevel(logging.DEBUG)\n\n# create formatter\nformatter = logging.Formatter('[%(asctime)s:%(name)s:%(levelname)s]: %(message)s')\n\n# add formatter to ch\ncon.setFormatter(formatter)\n\n# add ch to logger\nlogger.addHandler(con)\n\n\n#==============================================================================\n#%% Constants\n#==============================================================================\n\n\n\n\n#==============================================================================\n#%% Class definitions\n#==============================================================================\n\nclass DataSourceSelectorPanel(panel.PanelBase):\n \"\"\"\n Channel Selector panel\n \n It appears in the sidebar, usually as the current tab\n \n No __init__() required as it must be the same as the base class\n Must reimplement the drawPanel() method\n \n \"\"\"\n \n def drawPanel(self):\n \"\"\"\n Draw the GUI elements of the panel\n \n This is a Mandatory function. It will be called by ScopePy when\n the panel is added to a tab.\n \n \"\"\"\n \n \n # Setup model\n # Take the global sources structure in the API.dataStore \n self.model = DataSourcesTreeModel(self.API.dataStore.sources)\n self.model.source2node_function = self.API.dataStore.source_creators\n \n # Setup tree view\n self.treeView = QTreeView()\n self.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection)\n self.treeView.setSelectionBehavior(QTreeView.SelectItems)\n self.treeView.setItemsExpandable(True)\n self.treeView.setSizePolicy(QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Expanding))\n self.treeView.setContextMenuPolicy(Qt.CustomContextMenu)\n self.treeView.customContextMenuRequested.connect(self.openMenu)\n \n self.treeView.setModel(self.model)\n self.treeView.setColumnWidth(0,150)\n self.treeView.setColumnWidth(1,50)\n self.treeView.setWordWrap(True)\n #self.treeView.header().setStretchLastSection(False)\n \n \n \n # Expand the Home node by default\n self.treeView.expand(self.model.index(0,0,QModelIndex()))\n \n# addSourceButton = QPushButton(\"Add Source\")\n# self.connect(addSourceButton,SIGNAL(\"clicked()\"),self.addSource)\n \n deleteSourceButton = QPushButton(\"Delete Source\")\n self.connect(deleteSourceButton,SIGNAL(\"clicked()\"),self.deleteSource)\n \n \n topLabel = QLabel(\"Data &source selector\")\n topLabel.setBuddy(self.treeView)\n \n \n layout = QVBoxLayout()\n layout.addWidget(topLabel)\n layout.addWidget(self.treeView)\n layout.addWidget(deleteSourceButton)\n \n # Setup connections\n self.addCommsAction('update',self.update)\n self.addCommsAction('addSource',self.addSource)\n self.addCommsAction('deleteAllDataSources',self.deleteAllSources)\n \n \n self.setLayout(layout) \n \n \n def update(self):\n \"\"\"\n Update tree view\n \n \"\"\"\n \n self.treeView.update(QModelIndex())\n \n \n \n def openMenu(self, position):\n \"\"\"\n Context menu for tree view items\n Selects the content of the menu depending on the type of node.\n \n From \n https://wiki.python.org/moin/PyQt/Creating%20a%20context%20menu%20for%20a%20tree%20view\n \"\"\"\n \n # Get selected indices, but be careful it returns an index for \n # each column.\n indexes = self.treeView.selectedIndexes()\n #print(\"Number of indices selected: %i\" % len(indexes))\n \n if len(indexes) == 0:\n return\n \n # TODO: check the correct column\n \n node = self.model.getNode(indexes[0]) \n \n # Get menu from the node if it has one\n menu = node.menu()\n \n # Display menu if it exists\n # To facilitate nodes that can dynamically add children we call the \n # beginInsertRows/endInsertRows functions from the model. This means\n # that any command executed by the menus can add or remove child node\n # at this row of the TreeView.\n # This saves having to require that DataSourceNodes have references\n # to the DataSourcesTreeModel.\n if menu is not None:\n # Get the position of a new node, in case the menu actions\n # insert one\n nRows = node.childCount()\n \n # Prepare the tree view for the data structure to change\n self.model.beginInsertRows(indexes[0], nRows, nRows)\n \n # Execute a menu action\n menu.exec_(self.treeView.viewport().mapToGlobal(position)) \n \n # Tell tree view everything is done\n self.model.endInsertRows()\n \n \n \n def addSource(self,node,*parameters):\n \"\"\"\n Add a data source to list of data sources\n \n Inserts as a new child on the Home node\n \n Inputs\n ----------\n node : DatasourceNode derivative\n Node to be added to the tree\n \n *parameters: anything\n any parameters needed to create the source\n \n \"\"\"\n \n \n if node is None:\n return\n \n # Connect node to API\n # ----------------------------\n node.API = self.API\n \n # Add source to home node\n # ------------------------------\n \n # Get the home node\n homeNode_index = self.model.index(0,0,QModelIndex())\n homeNode = self.model.getNode(homeNode_index)\n position = homeNode.childCount()\n \n self.model.beginInsertRows(homeNode_index, position, position )\n \n homeNode.addChild(node)\n \n self.model.endInsertRows()\n \n\n\n def deleteSource(self):\n \"\"\"\n Delete selected source\n \n \"\"\"\n \n # Get selected indices, but be careful it returns an index for \n # each column.\n indexes = self.treeView.selectedIndexes()\n \n if len(indexes) == 0:\n return\n \n # TODO: check the correct column\n \n node = self.model.getNode(indexes[0])\n print(\"Node = %s, type = %s\" % (node.name(),node.typeInfo()))\n \n # Only proceed if a source is selected\n if not node.isSource:\n return\n \n print(\"Datasource to delete: [%s]\" % node.name())\n \n # Delete any table editors associated with this source\n for link in node.links:\n self.API.deleteMainAreaWindow(link)\n \n # Now delete the source from the tree\n parent_index = self.model.parent(indexes[0])\n \n self.model.removeRows(indexes[0].row(),1,parent_index)\n \n \n \n def deleteAllSources(self):\n \"\"\"\n Clear the Data source selector\n \n \"\"\"\n \n HomeNode_index = self.model.homeNode_index\n nRows = self.model.rowCount(HomeNode_index)\n \n # Remove data sources in the reverse order\n # this is necessary otherwise the model.index() function gets confused\n for row_index in range(nRows-1,-1,-1):\n # Get index of the node\n index = self.model.index(row_index,0,HomeNode_index)\n \n # Get the actual node\n node = self.model.getNode(index)\n \n # Delete any table editors associated with this source\n try:\n for link in node.links:\n self.API.deleteMainAreaWindow(link)\n except:\n logger.debug(\"Data source selector/deleteAllSources: Error when deleting source\")\n \n \n self.model.removeRows(index.row(),1,HomeNode_index)\n \n \n \n\n\n#==============================================================================\n#%% Data sources Tree model\n#==============================================================================\n\n# Columns\nTREE = 0\nATTRIBUTE_VALUE = 1\n\nclass DataSourcesTreeModel(QAbstractItemModel):\n \"\"\"\n Tree model for representing various data sources:\n HDF5 files, CSV, numpy arrays, pandas datasets\n \n \"\"\"\n \n \n def __init__(self, root, parent=None):\n \"\"\"\n INPUTS:\n ---------\n root : Node\n root of the tree\n \n \n parent : QObject\n \n \"\"\"\n super(DataSourcesTreeModel, self).__init__(parent)\n self._rootNode = root\n \n # Dictionary containing functions for converting different sources\n # into nodes\n # Supplied from API in the selector panel class\n self.source2node_function = {}\n \n \n\n \n def rowCount(self, parent):\n \"\"\"INPUTS: QModelIndex\"\"\"\n \"\"\"OUTPUT: int\"\"\"\n if not parent.isValid():\n parentNode = self._rootNode\n else:\n parentNode = parent.internalPointer()\n\n return parentNode.childCount()\n\n \n def columnCount(self, parent):\n \"\"\"INPUTS: QModelIndex\"\"\"\n \"\"\"OUTPUT: int\"\"\"\n # 2 column display\n return 2\n \n \n def data(self, index, role):\n \"\"\"INPUTS: QModelIndex, int\"\"\"\n \"\"\"OUTPUT: QVariant, strings are cast to QString which is a QVariant\"\"\"\n \n if not index.isValid():\n return None\n\n node = index.internalPointer()\n\n if role == Qt.DisplayRole or role == Qt.EditRole:\n if index.column() == TREE:\n return node.name()\n elif index.column()==ATTRIBUTE_VALUE:\n return node.value()\n \n # Return any icons that come with each node\n if role == Qt.DecorationRole:\n \n # Only use icons in the tree display\n if index.column() == TREE:\n if node.icon is not None:\n return node.icon\n\n\n \n def setData(self, index, value, role= Qt.EditRole):\n \"\"\"INPUTS: QModelIndex, QVariant, int (flag)\"\"\"\n\n if index.isValid():\n \n if role == Qt.EditRole:\n \n node = index.internalPointer()\n node.setName(value)\n \n return True\n return False\n\n \n \n def headerData(self, section, orientation, role):\n \"\"\"INPUTS: int, Qt::Orientation, int\"\"\"\n \"\"\"OUTPUT: QVariant, strings are cast to QString which is a QVariant\"\"\"\n if role == Qt.DisplayRole:\n if section == TREE:\n return \"Data source\"\n else:\n return \"Value\"\n\n \n \n \n def flags(self, index):\n \"\"\"INPUTS: QModelIndex\"\"\"\n \"\"\"OUTPUT: int (flag)\"\"\"\n return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable\n\n \n\n \n def parent(self, index):\n \"\"\"INPUTS: QModelIndex\"\"\"\n \"\"\"OUTPUT: QModelIndex\"\"\"\n \"\"\"Should return the parent of the node with the given QModelIndex\"\"\"\n \n node = self.getNode(index)\n parentNode = node.parent()\n \n if parentNode == self._rootNode:\n return QModelIndex()\n \n return self.createIndex(parentNode.row(), 0, parentNode)\n \n \n def index(self, row, column, parent):\n \"\"\"INPUTS: int, int, QModelIndex\"\"\"\n \"\"\"OUTPUT: QModelIndex\"\"\"\n \"\"\"Should return a QModelIndex that corresponds to the given row, column and parent node\"\"\"\n \n parentNode = self.getNode(parent)\n\n childItem = parentNode.child(row)\n\n\n if childItem:\n return self.createIndex(row, column, childItem)\n else:\n return QModelIndex()\n\n\n\n \n def getNode(self, index):\n \"\"\"CUSTOM\"\"\"\n \"\"\"INPUTS: QModelIndex\"\"\"\n \n if index.isValid():\n node = index.internalPointer()\n if node:\n return node\n \n return self._rootNode\n\n \n # TODO : insert and remove rows functions not implemented yet\n \n def insertRows(self, position, rows, parent= QModelIndex()):\n \"\"\"INPUTS: int, int, QModelIndex\"\"\"\n \n parentNode = self.getNode(parent)\n \n self.beginInsertRows(parent, position, position + rows - 1)\n \n for row in range(rows):\n \n childCount = parentNode.childCount()\n childNode = DatasourceNode(\"untitled\" + str(childCount))\n success = parentNode.insertChild(position, childNode)\n \n self.endInsertRows()\n\n return success\n \n \n\n \n def removeRows(self, position, rows, parent= QModelIndex()):\n \"\"\"INPUTS: int, int, QModelIndex\"\"\"\n \n parentNode = self.getNode(parent)\n self.beginRemoveRows(parent, position, position + rows - 1)\n \n for row in range(rows):\n success = parentNode.removeChild(position)\n \n self.endRemoveRows()\n \n return success\n \n # -------------------------------------------------------------------------\n # Custom functions\n # -------------------------------------------------------------------------\n @property\n def homeNode_index(self):\n \"\"\"\n Return the home node as a QModelIndex\n \n Output\n --------\n index : QModelIndex\n \n \"\"\"\n return self.index(0,0,QModelIndex())\n \n \n @property\n def homeNode(self):\n \"\"\"\n Return the Home node itself\n \n Output\n -------\n node : DatasourceNode()\n \n \"\"\"\n \n return self.getNode(self.homeNode_index)\n \n\n\n def addSource(self,source_type,*parameters):\n \"\"\"\n Add a data source to list of data sources\n \n Inserts as a new child on the Home node\n \n Inputs\n -------\n source_type : str\n label for the type of source\n \n *parameters: anything\n any parameters needed to create the source\n \n \"\"\"\n \n return \n \n \n \n # Call specific function for this source\n # ---------------------------------------\n \n # Make node from the source\n node = self.source2node_function[source_type](*parameters)\n \n if node is None:\n return\n \n # Add source to home node\n # ------------------------------\n \n # Get the home node\n homeNode_index = self.homeNode_index\n homeNode = self.getNode(homeNode_index)\n position = homeNode.childCount()\n \n self.beginInsertRows(homeNode_index, position, position )\n \n homeNode.addChild(node)\n \n self.endInsertRows()\n\n#==============================================================================\n#%% Help docs\n#==============================================================================\n\nhelp_doc = \"\"\"\n\n%*% Data sources browser\n\n++<\nThis panel displays \"data sources\" that have been loaded into ScopePy. A data source\nis a container for tabular data. The data in data source can usually be viewed\nin a table, via the table editor panel. From here it can be selected and made into\nchannels for plotting.\n>++\n\n++<\nData sources can be files, data sent over the network, or created programmatically.\nEach different type of source appears as a different branch in the tree diagram.\nSome data sources, e.g. HDF5 files, contain multiple tables or datasets. These\ncan be accessed by expanding sub branches on the tree. Other sources, e.g. CSV files\nhave only one entry on the tree.\n>++\n\n%*% Tree diagram description\n++<\nThe tree diagram display has a root node, called 'Home'. When a data source is\naccessed, either by loading a file, receiving a network packet, or being created\nfrom a script, then a new branch will appear under the Home node, with an icon\nthat represents the type of source.\n>++\n\n++<\nDepending on the type of source, some branches will have sub branches. These can\nbe either\n--<\n\n--+ Tag: Usually a text string contained in the file. Its value is displayed in the left hand column.\n--+ Table: A table of numeric data that can be opened using the table editor by right clicking.\n--+ Folder: A sub folder of the data source\n>--\n>++\n\n\n\n\"\"\"\n\n\n#==============================================================================\n#%% Panels to export\n#==============================================================================\n# Put any panels to be imported from this file here\n# Note: this must go after the class definitions\n#\n# Panels are passed in a dictionary where:\n# key = the name to be used on menus\n# value = class reference\n\n__panels__ = {\"&Data Source Selector\":panel.PanelFlags(DataSourceSelectorPanel,\n open_on_startup=True,\n single_instance=True,\n on_panel_menu=False,\n location='sidebar',\n API_attribute_name='dataSourceSelector',\n docs=help_doc)}\n","repo_name":"TriangleDot/ScopePy","sub_path":"panels/data_source_selector.py","file_name":"data_source_selector.py","file_ext":"py","file_size_in_byte":18193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"36269831737","text":"#coding:utf8\r\n'''\r\nCreated on 2012-9-11\r\n\r\n@author: Administrator\r\n'''\r\nfrom app.scense.serverconfig.node import nodeHandle\r\nfrom app.scense.applyInterface import campaign\r\nfrom app.scense.netInterface.pushObjectNetInterface import pushOtherMessage\r\nfrom app.scense.protoFile.campaign import GetCityListInfo4402_pb2,GetGroupLingDiInfo4400_pb2,\\\r\nObtainJiangLi4401_pb2,GroupPK4403_pb2,GetXuYuanInfo4404_pb2,UseXingYun4405_pb2,\\\r\nGetBattleInfo4406_pb2,JoinBattle4407_pb2,CancelBattle4409_pb2,AutoJoinBattle4408_pb2\r\n\r\n@nodeHandle\r\ndef GetGroupLingDiInfo_4400(dynamicId, request_proto):\r\n '''获取国领地信息\r\n '''\r\n argument = GetGroupLingDiInfo4400_pb2.GetGroupLingDiInfoRequest()\r\n argument.ParseFromString(request_proto)\r\n response = GetGroupLingDiInfo4400_pb2.GetGroupLingDiInfoResponse()\r\n characterId = argument.id\r\n data = campaign.GetGroupLingDiInfo4400(dynamicId, characterId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n if data.get('data',None):\r\n LingdiInfo = data.get('data')\r\n response.groupInfo.ldType = LingdiInfo['ldType']\r\n response.groupInfo.groupName = LingdiInfo['groupName']\r\n response.groupInfo.groupLevel = LingdiInfo['groupLevel']\r\n response.groupInfo.groupLeader = LingdiInfo['groupLeader']\r\n response.groupInfo.obtainJL = LingdiInfo['obtainJL']\r\n response.groupInfo.icon = LingdiInfo['icon']\r\n response.groupInfo.battleInfo.extend(LingdiInfo['battleInfo'])\r\n response.groupInfo.battleTime = LingdiInfo['battleTime']\r\n return response.SerializeToString()\r\n\r\n@nodeHandle\r\ndef ObtainJiangLi_4401(dynamicId, request_proto):\r\n '''获取国领地奖励\r\n '''\r\n argument = ObtainJiangLi4401_pb2.ObtainJiangLiRequest()\r\n argument.ParseFromString(request_proto)\r\n response = ObtainJiangLi4401_pb2.ObtainJiangLiResponse()\r\n characterId = argument.id\r\n data = campaign.GetCityListInfo4402(dynamicId, characterId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n return response.SerializeToString()\r\n\r\n\r\n@nodeHandle\r\ndef GetCityListInfo_4402(dynamicId, request_proto):\r\n '''获取城镇征战列表\r\n '''\r\n argument = GetCityListInfo4402_pb2.GetCityListInfoRequest()\r\n argument.ParseFromString(request_proto)\r\n response = GetCityListInfo4402_pb2.GetCityListInfoResponse()\r\n characterId = argument.id\r\n data = campaign.GetCityListInfo4402(dynamicId, characterId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n if data.get('data',None):\r\n cityinfos = data.get('data')\r\n for city in cityinfos:\r\n cityinof = response.cityInfo.add()\r\n cityinof.lzName = city.get('kimoriname')\r\n cityinof.lzIcon = city.get('kimoriemblem')\r\n cityinof.tzName = city.get('siegename')\r\n cityinof.tzIcon = city.get('siegeemblem')\r\n cityinof.btnState = city.get('fortressstatus')\r\n return response.SerializeToString()\r\n \r\n\r\n@nodeHandle\r\ndef GroupPK_4403(dynamicId, request_proto):\r\n '''国战申请\r\n '''\r\n argument = GroupPK4403_pb2.GroupPKRequest()\r\n argument.ParseFromString(request_proto)\r\n response = GroupPK4403_pb2.GroupPKResponse()\r\n characterId = argument.id\r\n pkId = argument.pkId\r\n data = campaign.GroupPK4403(dynamicId, characterId, pkId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n return response.SerializeToString()\r\n\r\n@nodeHandle\r\ndef GetXuYuanInfo_4404(dynamicId, request_proto):\r\n '''获取许愿信息\r\n '''\r\n argument = GetXuYuanInfo4404_pb2.GetXuYuanInfoRequest()\r\n argument.ParseFromString(request_proto)\r\n response = GetXuYuanInfo4404_pb2.GetXuYuanInfoResponse()\r\n characterId = argument.id\r\n data = campaign.GetXuYuanInfo4404(dynamicId, characterId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n if data.get('data',None):\r\n xuyuanInfos = data.get('data')\r\n response.xuYuanInfo.xyValue = xuyuanInfos.get('xyValue',0)\r\n usedInfo = response.xuYuanInfo.usedInfo\r\n for xuyuan in xuyuanInfos.get('cliffordLog',{}):\r\n xuyuanResponse = usedInfo.add()\r\n xuyuanResponse.name = xuyuan.get('name','')\r\n xuyuanResponse.type = xuyuan.get('type','')\r\n return response.SerializeToString()\r\n\r\n@nodeHandle\r\ndef UseXingYun_4405(dynamicId, request_proto):\r\n '''使用幸运许愿\r\n '''\r\n argument = UseXingYun4405_pb2.UseXingYunRequest()\r\n argument.ParseFromString(request_proto)\r\n response = UseXingYun4405_pb2.UseXingYunResponse()\r\n characterId = argument.id\r\n usetype = argument.type\r\n data = campaign.UseXingYun4405(dynamicId, characterId, usetype)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n return response.SerializeToString()\r\n\r\n@nodeHandle\r\ndef GetBattleInfo_4406(dynamicId, request_proto):\r\n '''获取国战的信息\r\n '''\r\n argument = GetBattleInfo4406_pb2.GetBattleInfoRequest()\r\n argument.ParseFromString(request_proto)\r\n response = GetBattleInfo4406_pb2.GetBattleInfoResponse()\r\n characterId = argument.id\r\n data = campaign.GetBattleInfo4406(dynamicId, characterId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n if data.get('data',None):\r\n BattleInfos = data.get('data')\r\n dataResponse = response.groupBattleInfo\r\n dataResponse.roundCount = BattleInfos.get('roundCount')\r\n dataResponse.remainTime = BattleInfos.get('remainTime')\r\n dataResponse.jishaCount = BattleInfos.get('jishaCount')\r\n dataResponse.failCount = BattleInfos.get('failCount')\r\n dataResponse.obtainCoin = BattleInfos.get('obtainCoin')\r\n dataResponse.obtainSw = BattleInfos.get('obtainSw')\r\n \r\n battleListResponse = dataResponse.battleInfoList\r\n for battleInfo in BattleInfos['battleInfoList']:\r\n battleResponse = battleListResponse.add()\r\n battleResponse.roleId1 = battleInfo.get('roleId1')\r\n battleResponse.roleName1 = battleInfo.get('roleName1')\r\n battleResponse.roleId2 = battleInfo.get('roleId2')\r\n battleResponse.roleName2 = battleInfo.get('roleName2')\r\n battleResponse.sucObCoin = battleInfo.get('sucObCoin')\r\n \r\n guild1Info = BattleInfos['group1Info']\r\n group1InfoResponse = dataResponse.group1Info\r\n group1InfoResponse.groupName = guild1Info.get('groupName',u'')\r\n group1InfoResponse.groupCount = guild1Info.get('groupCount',0)\r\n group1InfoResponse.icon = guild1Info.get('icon',0)\r\n group1MemberListResponse = group1InfoResponse.groupMember\r\n for role in guild1Info.get('groupMember',[]):\r\n roleResponse = group1MemberListResponse.add()\r\n roleResponse.memberId = role['memberId']\r\n roleResponse.memberName = role['memberName']\r\n \r\n guild2Info = BattleInfos['group2Info']\r\n group2InfoResponse = dataResponse.group2Info\r\n group2InfoResponse.groupName = guild2Info.get('groupName',u'')\r\n group2InfoResponse.groupCount = guild2Info.get('groupCount',0)\r\n group2InfoResponse.icon = guild2Info.get('icon',0)\r\n group2MemberListResponse = group2InfoResponse.groupMember\r\n for role in guild2Info.get('groupMember',[]):\r\n roleResponse = group2MemberListResponse.add()\r\n roleResponse.memberId = role['memberId']\r\n roleResponse.memberName = role['memberName']\r\n \r\n return response.SerializeToString()\r\n\r\n@nodeHandle\r\ndef Participate_4407(dynamicId, request_proto):\r\n '''角色参战\r\n '''\r\n argument = JoinBattle4407_pb2.JoinBattleRequest()\r\n argument.ParseFromString(request_proto)\r\n response = JoinBattle4407_pb2.JoinBattleResponse()\r\n characterId = argument.id\r\n data = campaign.Participate4407(dynamicId, characterId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n return response.SerializeToString()\r\n\r\n@nodeHandle\r\ndef AutoJoinBattle_4408(dynamicId, request_proto):\r\n '''自动参战或取消自动参战\r\n '''\r\n argument = AutoJoinBattle4408_pb2.AutoJoinBattleRequest()\r\n argument.ParseFromString(request_proto)\r\n response = AutoJoinBattle4408_pb2.AutoJoinBattleResponse()\r\n characterId = argument.id\r\n autoJoinFlag = argument.autoJoinFlag\r\n data = campaign.AutoJoinBattle4408(dynamicId, characterId, autoJoinFlag)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n return response.SerializeToString()\r\n\r\n@nodeHandle\r\ndef CancelBattle_4409(dynamicId, request_proto):\r\n '''角色参战\r\n '''\r\n argument = CancelBattle4409_pb2.CancelBattleRequest()\r\n argument.ParseFromString(request_proto)\r\n response = CancelBattle4409_pb2.CancelBattleResponse()\r\n characterId = argument.id\r\n data = campaign.CancelParticipate4409(dynamicId, characterId)\r\n \r\n response.result = data.get('result',False)\r\n msg = data.get('message','')\r\n if msg:\r\n pushOtherMessage(905, msg, [dynamicId])\r\n response.message = msg\r\n return response.SerializeToString()\r\n\r\n\r\n\r\n\r\n \r\n ","repo_name":"9miao/firefly_fengyan_OL","sub_path":"server/fengyanOL/app/scense/nodeapp/campaign.py","file_name":"campaign.py","file_ext":"py","file_size_in_byte":10158,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"85"} +{"seq_id":"15986470386","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport os\nimport sys\nimport tempfile\nimport time\nfrom math import sqrt\n\nimport cv2\nimport numpy as np\nimport youtube_dl\n\nfrom palette import palette\n\npalette = np.asarray(palette)\ngreen_colors = [2, 10, 22, 28, 29, 34, 35, 36, 40, 41, 42, 43, 46, 47, 48, 49, 50, 58, 64, 65, 70, 71, 72, 76, 77, 78, 79, 82, 83, 84, 85, 100, 106, 107, 108, 112, 113, 114, 115, 118, 119, 120, 121, 142, 143, 148, 149, 150, 154, 155, 156, 157]\n# green_colors = [2, 10, 22, 28, 29, 34, 35, 36, 40, 41, 42, 46, 47, 48, 49, 58, 64, 65, 70, 71, 72, 76, 77, 82, 83, 84, 101, 106, 107, 112, 113, 114, 118, 119, 120, 142, 143, 148, 149, 150, 154, 155, 156]\n# green_colors = [2, 10, 22, 28, 29, 34, 35, 40, 41, 42, 46, 47, 48, 64, 70, 71, 76, 77, 82, 83, 106, 112, 113, 118, 119, 148, 149, 154, 155]\n# green_colors = [2, 10, 22, 28, 34, 35, 40, 41, 46, 47, 70, 76, 77, 82, 83, 112, 113, 118, 154]\n\n\ndef closest_color(color):\n deltas = palette - color\n dist_2 = np.einsum('ij,ij->i', deltas, deltas)\n return np.argmin(dist_2)\n\n\ndef display_image(image, width, height, green_bg=False):\n # Make output buffer\n buffer = ''\n for y in range(len(image)):\n for x in range(len(image[0])):\n pixel = image[y][x]\n pixel = pixel[2], pixel[1], pixel[0]\n index = closest_color(pixel)\n if green_bg and index in green_colors:\n buffer += f' '\n else:\n buffer += f'\\033[48;5;{index}m \\033[0m'\n buffer += '\\n'\n # Display image\n print(buffer[:-1], end='')\n\n\ndef display_video(video_path, frame_rate=300, green_bg=False):\n # Get screen size\n columns, rows = os.get_terminal_size(0)\n # Display video\n prev = 0\n capture = cv2.VideoCapture(video_path)\n while True:\n time_elapsed = time.time() - prev\n ret, frame = capture.read()\n if ret:\n if time_elapsed > 1./frame_rate:\n resized = cv2.resize(frame, (columns, rows))\n display_image(resized, columns, rows, green_bg)\n prev = time.time()\n else:\n break\n\ndef download_youtube_video(url, max_video_height=360):\n tmp_video_filename = tempfile.mktemp(dir='/tmp')\n\n ydl_opts = {\n 'format': f'bestvideo[height<={max_video_height}]',\n 'outtmpl': tmp_video_filename\n }\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([url])\n\n return tmp_video_filename\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print('Usage: %s ' % sys.argv[0])\n sys.exit(1)\n\n video_file = download_youtube_video(sys.argv[1])\n display_video(video_file, green_bg=False)\n os.remove(video_file)\n","repo_name":"b0oml/TERMVideo","sub_path":"displayvideo.py","file_name":"displayvideo.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22781550440","text":"from sense_hat import SenseHat\nfrom time import sleep\nimport CoapClientApp\nimport senseme\n\n#this class has a function whilch will be used in other class to call and run all the sensors and get values\nclass SensorAdaptor():\n def runme(self):\n while 1:\n temp = senseme.sensorFunction()\n #check if temp is greater than 25 , if so call teh client app to send data\n if(temp>25):\n CoapClientApp.startApp()\n #check if acclerometer reading , if so call teh client app to send data\n elif(senseme.intruderFunction()==1):\n CoapClientApp.startApp()\n else:\n sense.clear()\n break\n","repo_name":"joshisujay1996/iot-devices","sub_path":"Connected_project/pi/SensorAdaptor.py","file_name":"SensorAdaptor.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3633637997","text":"import numpy as np\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore.common import dtype as mstype\nfrom mindspore.ops import operations as P\nfrom mindspore.common.initializer import TruncatedNormal\n\ndef _bn(channel):\n return nn.BatchNorm2d(channel, eps=1e-4, momentum=0.9, gamma_init=1, beta_init=0, moving_mean_init=0,\n moving_var_init=1)\n\nclass Conv(nn.Cell):\n def __init__(self, in_channel, out_channel, kernel_size=3, stride=1, use_bn=False, pad_mode='same'):\n super(Conv, self).__init__()\n self.conv = nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, stride=stride,\n padding=0, pad_mode=pad_mode, weight_init=TruncatedNormal(0.02))\n self.bn = _bn(out_channel)\n self.Relu = nn.ReLU()\n self.use_bn = use_bn\n def construct(self, x):\n out = self.conv(x)\n if self.use_bn:\n out = self.bn(out)\n out = self.Relu(out)\n return out\n\nclass VGG(nn.Cell):\n \"\"\"VGG Network structure\"\"\"\n def __init__(self, is_training=True):\n super(VGG, self).__init__()\n self.conv1 = Conv(3, 64, use_bn=True)\n self.conv2 = Conv(64, 128, use_bn=True)\n self.conv3 = Conv(128, 256, use_bn=True)\n self.conv4 = Conv(256, 256, use_bn=True)\n self.conv5 = Conv(256, 512, use_bn=True)\n self.conv6 = Conv(512, 512, use_bn=True)\n self.conv7 = Conv(512, 512, kernel_size=2, pad_mode='valid', use_bn=True)\n self.maxpool2d1 = nn.MaxPool2d(kernel_size=2, stride=2, pad_mode='same')\n self.maxpool2d2 = nn.MaxPool2d(kernel_size=(2, 1), stride=(2, 1), pad_mode='same')\n self.bn1 = _bn(512)\n\n def construct(self, x):\n x = self.conv1(x)\n x = self.maxpool2d1(x)\n x = self.conv2(x)\n x = self.maxpool2d1(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.maxpool2d2(x)\n x = self.conv5(x)\n x = self.conv6(x)\n x = self.maxpool2d2(x)\n x = self.conv7(x)\n return x\n\n\nclass BidirectionalLSTM(nn.Cell):\n\n def __init__(self, nIn, nHidden, nOut, batch_size):\n super(BidirectionalLSTM, self).__init__()\n\n self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True)\n self.embedding = nn.Dense(in_channels=nHidden * 2, out_channels=nOut)\n self.h0 = Tensor(np.zeros([1 * 2, batch_size, nHidden]).astype(np.float32))\n self.c0 = Tensor(np.zeros([1 * 2, batch_size, nHidden]).astype(np.float32))\n\n def construct(self, x):\n recurrent, _ = self.rnn(x, (self.h0, self.c0))\n T, b, h = P.Shape()(recurrent)\n t_rec = P.Reshape()(recurrent, (T * b, h,))\n\n out = self.embedding(t_rec) # [T * b, nOut]\n out = P.Reshape()(out, (T, b, -1,))\n\n return out\n\n\nclass CRNN(nn.Cell):\n \"\"\"\n Define a CRNN network which contains Bidirectional LSTM layers and vgg layer.\n\n Args:\n input_size(int): Size of time sequence. Usually, the input_size is equal to three times of image height for\n text images.\n batch_size(int): batch size of input data, default is 64\n hidden_size(int): the hidden size in LSTM layers, default is 512\n \"\"\"\n def __init__(self, config):\n super(CRNN, self).__init__()\n self.batch_size = config.batch_size\n self.input_size = config.input_size\n self.hidden_size = config.hidden_size\n self.num_classes = config.class_num\n self.reshape = P.Reshape()\n self.transpose = P.Transpose()\n self.vgg = VGG()\n self.rnn = nn.SequentialCell([\n BidirectionalLSTM(self.input_size, self.hidden_size, self.hidden_size, self.batch_size),\n BidirectionalLSTM(self.hidden_size, self.hidden_size, self.num_classes, self.batch_size)])\n\n def construct(self, x):\n x = self.vgg(x)\n\n x = self.reshape(x, (self.batch_size, self.input_size, -1))\n x = self.transpose(x, (2, 0, 1))\n\n x = self.rnn(x)\n\n return x\n\n\ndef crnn(config, full_precision=False):\n \"\"\"Create a CRNN network with mixed_precision or full_precision\"\"\"\n net = CRNN(config)\n if not full_precision:\n net = net.to_float(mstype.float16)\n return net\n","repo_name":"lixiao-yang/LZU-MindSpore","sub_path":"model_zoo/official/cv/crnn/src/crnn.py","file_name":"crnn.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"31773146959","text":"root = [1,2,3,4,5]\n\ndef test(input:list):\n print(id(input))\n\n temp = [input]\n print(id(temp[0]))\n\n for i in temp:\n for j in range(len(i)):\n print(j)\n input[j] += 1\n\n return input\n\nprint(test(root))","repo_name":"jihuncha/Data_Structure","sub_path":"com/codingTest/reminder/just_practice/211125_test.py","file_name":"211125_test.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"39612546789","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution:\n def maxDepth(self, root: 'Node') -> int:\n if not root:\n return 0\n queue = deque()\n queue.append(root)\n depth = 0\n while queue:\n for i in range(len(queue)):\n current_node = queue.popleft()\n if current_node.children:\n for child in current_node.children:\n queue.append(child)\n depth += 1\n return depth","repo_name":"ahlee-shawn/LeetCoder","sub_path":"BFS/559.py","file_name":"559.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"26560992205","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport unittest\n\n\ndef f(x):\n return 1\n\n\n#make a class with tests\nclass _generic_test_stuff(unittest.TestCase):\n \"\"\"\n Class containing unittests\n \"\"\"\n\n #tests should begin with test_\n def test_f(self):\n \"\"\"\n Convert isin to Morningstar security id, scrapge morningstar page and test for same isin\n \"\"\"\n self.assertEqual(f(3),1)\n\n\nif __name__ == \"__main__\":\n _run_unit_tests=True\n _test_only = list() # if list is empty then test all\n #test_only.append('test_transform_shape')\n if _run_unit_tests:\n if len(_test_only) > 0:\n _suite = unittest.TestSuite()\n for ut in _test_only:\n _suite.addTest(_generic_test_stuff(ut))\n unittest.TextTestRunner().run(_suite)\n else:\n #unittest.main()\n _suite = unittest.TestLoader().loadTestsFromTestCase(_generic_test_stuff)\n unittest.TextTestRunner(verbosity=2).run(_suite)\n else:\n #do something else\n pass","repo_name":"rucsa/thesis_benchmark_advisor","sub_path":"tests/suite1.py","file_name":"suite1.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"24437589594","text":"class Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n if amount == 0:\n return 0\n # we will use a list, dp, to keep track of the minimum number of coins needed\n # dp[i] will represent the minimum number of coins needed to sum to i\n # originally, every index from 1 to amount will need to be infinity since we have no way to sum\n dp = defaultdict(lambda: inf)\n \n # for every coin, we will update dp\n for c in coins:\n # we only care if the coin is worth less than our amount, otherwise we can't use it\n if c <= amount:\n # it takes only 1 coin to sum to this coin's value\n dp[c] = 1\n \n # for all values from c+1 to amount (we don't care about smaller or bigger values)\n for i in range(c+1,amount+1):\n # see if we can sum to i using fewer coins\n # if dp[i-c] isn't infinity, then we can use our new coin to sum to i\n # this takes 1 extra coin, so we check if 1 + dp[i-c] is less than dp[i]\n dp[i] = min(dp[i], 1+dp[i-c])\n \n # if we never found a valid combination then we return -1\n if dp[amount] == inf:\n return -1\n \n # otherwise just return the min number of coins to sum to amount!\n return dp[amount]","repo_name":"Bloomh/LeetCode-Submissions","sub_path":"0322-coin-change/0322-coin-change.py","file_name":"0322-coin-change.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5233948587","text":"from enum import Enum\n\n\nclass VariableType(Enum):\n const = 1\n notConst = 2\n \nclass PrismVariable(object):\n\n def __init__(self):\n self.name = None\n self.value = None\n self.minValue = None\n self.maxValue = None\n self.initValue = None\n self.varType = None\n self.subType = None\n self.operator = '='\n\n \n\n def getAssignment(self,v,isInt):\n value = None\n #print(isinstance(v,PrismVariable))\n if type(v) is PrismVariable:\n value = v\n else:\n if v is not None:\n if isInt:\n value = int(v)\n else:\n value = float(v)\n return value\n \n\n \n def create(self,n,v,minv,maxv,initv,t,subT):\n #print n\n #print v\n #print minv\n #print maxv\n #print initv\n #print t\n \n self.name = n\n self.subType = subT\n self.varType = t\n \n isInt = False\n if(subT == \"int\"):\n isInt = True\n\n #print minv\n #print type(minv)\n #assign v\n self.value = self.getAssignment(v,isInt)\n \n #assign initv\n self.initValue = self.getAssignment(initv,isInt)\n\n #assign minv\n self.minValue = self.getAssignment(minv,isInt)\n\n self.maxValue = self.getAssignment(maxv,isInt)\n\n\n def createUsingOtherPrismVariable(self,var,v):\n if type(var) is PrismVariable:\n self.assign(var)\n self.value = v \n\n def stateString(self,isDest):\n toret = '('+self.name;\n if isDest:\n toret = toret + \"'\"\n toret = toret + self.operator+self.getStringRep(self.value)+\")\"\n return toret\n \n \n def prismString(self):\n if self.varType is VariableType.const:\n if self.subType is None:\n return \"const \"+self.name+\" = \"+self.getStringRep(self.value)+\";\"\n else:\n return \"const \"+self.subType+\" \"+self.name+\" = \"+self.getStringRep(self.value)+\";\"\n else:\n toret = self.name+\":[\";\n toret = toret + self.getStringRep(self.minValue);\n toret = toret + \" .. \" + self.getStringRep(self.maxValue)+\"]\"\n toret = toret + \" init \"+self.getStringRep(self.initValue)+\";\"\n return toret\n \n\n def getStringRep(self,var):\n if type(var) is str:\n return var\n elif type(var) is float:\n return str(var)\n elif type(var) is int:\n return str(var)\n elif type(var) is PrismVariable:\n \n return self.getStringRep(var.name)\n return \"\"\n\n\n def getRangeValues(self):\n r = []\n if type(self.minValue) is PrismVariable:\n r.append(self.minValue.value)\n else:\n r.append(self.minValue)\n if type(self.maxValue) is PrismVariable:\n r.append(self.maxValue.value)\n else:\n r.append(self.maxValue)\n return r \n \n \n def assign(self,var):\n if type(var) is PrismVariable:\n self.name = var.name\n self.initValue = var.initValue\n self.minValue = var.minValue\n self.maxValue = var.maxValue\n self.value = var.value\n self.varType = var.varType\n self.subType = var.subType\n\n \n def equals(self,var,justName=False):\n if type(var) is PrismVariable:\n if (self.name == var.name):\n if justName:\n return True\n else:\n #print self.value\n #print var.value \n if(self.value == var.value):\n return True\n else:\n return False \n return False\n \n def __repr__(self):\n return self.__str__()\n \n\n def __str__(self):\n \n #if type(self.value) == PrismVariable:\n # return self.name+\":\"+str(self.value)\n \n if self.varType == VariableType.const:\n return self.name + \":\"+self.getStringRep(self.value)+\"(\"+self.getStringRep(self.initValue)+ \")\"\n else:\n return self.getStringRep(self.name) + \":\"+self.getStringRep(self.value)+\"(\"+ self.getStringRep(self.initValue)+ \") range:[\"+self.getStringRep(self.minValue)+\",\"+self.getStringRep(self.maxValue)+\"]\"\n \n","repo_name":"fatmaf/generatedTests","sub_path":"wkspace/PrismVariable.py","file_name":"PrismVariable.py","file_ext":"py","file_size_in_byte":4487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26915407939","text":"from django.conf.urls import url\n\nfrom . import views\n\n\nurlpatterns = [\n url(r'^', views.index, name='index'),\n url(r'^hello_world/$', views.hello_world),\n url(r'^signup/$', views.signup, name='signup'),\n url(r'^user/(?P.+)/$', views.user_page),\n url(r'^org/(?P.+/?P.+/?P.+)/', views.mtgminutesitem_view),\n url(r'^org/(?P.+/?P.+)/', views.organization_view),\n url(r'^org/(?P.+)/', views.organization_view),\n]\n\n'''\ndef user_page(request):\n # display the user page\n context = {}\n return render(request, 'minutes/user_view.html', context)\n\ndef organization_view(request):\n # desplay the organization_view\n context = {}\n return render(request, 'minutes/organization_view.html', context)\n\ndef mtgminutes_view(request):\n # display the mtgminutes_view\n context = {}\n return render(request, 'minutes/mtgminutes_view.html',context)\n\ndef mtgminutesitem_view(request):\n'''\n","repo_name":"NotAnAmbiTurner/sscrum2015","sub_path":"minutes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4517741544","text":"import os\n\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.txt')).read()\nCHANGES = open(os.path.join(here, 'CHANGES.txt')).read()\n\nrequires = [\n 'pyramid',\n 'SQLAlchemy',\n 'transaction',\n 'pyramid_tm',\n 'pyramid_debugtoolbar',\n 'zope.sqlalchemy',\n 'waitress',\n 'docutils',\n 'WTForms',\n 'alembic',\n 'boto',\n ]\n\nsetup(name='volunteer',\n version='0.0.6',\n description='volunteer',\n long_description=README + '\\n\\n' + CHANGES,\n classifiers=[\n \"Programming Language :: Python\",\n \"Framework :: Pylons\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n ],\n author='Peter Smit',\n author_email='peter@smitmail.eu',\n url='',\n keywords='',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n test_suite='volunteer',\n install_requires=requires,\n entry_points=\"\"\"\\\n [paste.app_factory]\n main = volunteer:main\n [console_scripts]\n initialize_volunteer_db = volunteer.scripts.initializedb:main\n send_notifications = volunteer.scripts.send_notifications:main\n send_test_sms = volunteer.scripts.send_test_sms:main\n fix_delivery_message_links = volunteer.scripts.fix_delivery_message_links:main\n \"\"\",\n)\n\n","repo_name":"psmit/volunteer","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"525770788","text":"# max element\r\n\r\n# a = [1, 22, 63, 34, 55]\r\n# max = a[0]\r\n# for i in a:\r\n# if max < i:\r\n# max = i\r\n# print(max)\r\n\r\n\r\n# a = [5, 8, 20, 10]\r\n\r\n\r\n# for i in a:\r\n# flag = True\r\n# for j in a:\r\n# if i < j:\r\n# flag = False\r\n# break\r\n\r\n# if flag == True:\r\n# print(i)\r\n# break\r\n\r\n\r\n# a = [10, 10, 10]\r\n\r\n# l1 = a[0]\r\n# l2 = -1\r\n\r\n# for i in range(1, len(a)):\r\n# if a[i] == l1:\r\n# continue\r\n# if a[i] > l1:\r\n# l2 = l1\r\n# l1 = a[i]\r\n# elif a[i] > l2:\r\n# l2 = a[i]\r\n# if l2 == -1:\r\n# print(\"No second large\")\r\n# else:\r\n# print(l2)\r\n\r\n\r\n# a = [8, 12, 12, 15]\r\n\r\n# flag = True\r\n\r\n# for i in range(0, len(a)-1):\r\n# if a[i] > a[i+1]:\r\n# flag = False\r\n# break\r\n\r\n# print(flag)\r\n\r\n\r\n# a = [2, 3, 4, 5, 6]\r\n# temp=[]\r\n\r\n# for i in reversed(range(len(a))):\r\n# temp.append(a[i])\r\n\r\n# print(temp)\r\n# i = 0\r\n# j = len(a)-1\r\n# while(i < j):\r\n# temp = a[i]\r\n# a[i] = a[j]\r\n# a[j] = temp\r\n# i += 1\r\n# j -= 1\r\n\r\n# print(a)\r\n\r\n\r\na = [10, 20, 20, 20, 30, 30, 30, 30]\r\n\r\n# temp = []\r\n\r\n# for i in range(len(a)):\r\n# if i == 0:\r\n# temp.append(a[i])\r\n# if a[i] != temp[len(temp)-1]:\r\n# temp.append(a[i])\r\n\r\n# print(temp)\r\n\r\n\r\n# for i in range(len(a)):\r\n# if i == 0:\r\n# print(a[i])\r\n# continue\r\n# if a[i] != a[i-1]:\r\n# print(a[i])\r\n# a=[10,10,10,20]\r\n# j = 0\r\n\r\n# for i in range(len(a)):\r\n# if i == 0:\r\n# a[j] = a[i]\r\n# j += 1\r\n# continue\r\n# if a[i] != a[i-1]:\r\n# a[j] = a[i]\r\n# j += 1\r\n\r\n# print(a)\r\n\r\n\r\n# a = [7, 10, 4, 3, 6, 5, 2]\r\n# number=-1\r\n# for i in reversed(range(len(a))):\r\n# if a[i]>number:\r\n# print(a[i])\r\n# number=a[i]\r\n\r\n\r\na = [7, 9, 5, 6, 3, 2, 17]\r\n\r\nmin_v = a[0] # 30\r\nres = a[1] - a[0] # -20\r\nfor i in range(1, len(a)):\r\n if a[i] - min_v > res:\r\n res = a[i] - min_v\r\n else:\r\n min_v = min(min_v, a[i])\r\n\r\nprint(res)\r\n","repo_name":"rameswar09/python_test","sub_path":"Basic-python/array.py","file_name":"array.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"75083647958","text":"import csv\nimport os\nimport pandas as pd\n\n# cities_csv = os.path.join(\"..\", \"Resources\", \"assets\", \"cities.csv\")\n# with open(cities_csv_path, newline=\"\") as csvfile:\n# csv_reader = csv.reader(csvfile, delimiter=\",\")\n\n# df = pd.read_csv(file, encoding=\"ISO-8859-1\")\n\n\ncities_csv = \"Resources/cities.csv\"\ncities_df = pd.read_csv(cities_csv)\ncities_df.head()\n\nhtml = cities_df.to_html()\nW_data = open(\"weather_data.html\", \"w\")\nW_data.write(html)\nW_data.close()\n\nos.getcwd()\n\n\n","repo_name":"Kenneth-Edwards/Web-Dashboard-using-Bootstrap-CSS-and-Responsive-design","sub_path":"Web_Visualizations/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"72539156118","text":"import gym\r\nfrom gym import spaces\r\nfrom car_controller import Car\r\nimport numpy as np\r\nfrom stable_baselines3.common.env_checker import check_env\r\nimport math\r\nfrom stable_baselines3 import DQN\r\n\r\nclass AutoParkEnv(gym.Env):\r\n \"\"\"Custom Environment that follows gym interface\"\"\"\r\n metadata = {'render.modes': ['human']}\r\n\r\n def __init__(self):\r\n super(AutoParkEnv, self).__init__()\r\n # Define action and observation space\r\n # They must be gym.spaces objects\r\n # Example when using discrete actions:\r\n self.action_space = spaces.Discrete(2)\r\n # Example for using image as input (channel-first; channel-last also works):\r\n self.observation_space = spaces.Dict({\r\n 'position':spaces.Box(low=np.array([-1.0, -3.0]), high=np.array([5.0, 2.0]),dtype=np.float64),\r\n 'sensor':spaces.Box(low=0.0,high=1024.0,shape=(16,),dtype=np.float64),\r\n 'orientation':spaces.Box(low=-0.5,high=4.0,shape=(1,),dtype=np.float64)\r\n })\r\n self.car=Car()\r\n self.gobackward=0\r\n self.turn=1\r\n def compute_reward(self,observation,collision):\r\n position=observation[\"position\"]\r\n orientation=observation[\"orientation\"]\r\n x=position[0]\r\n y=position[1]\r\n angle=orientation[0]\r\n done=0\r\n reward=0\r\n if x >= -2.5 and x <= 0.4 and angle<0: #提前转向进不去\r\n reward=-100*(0.4-x)#他以为这样好 x=0.4是为0,之前为负数\r\n done=1\r\n elif x >= -2.5 and x <= 1.6 and angle>2: #正确前进\r\n reward=100*(1-x)\r\n done=0\r\n elif x >= 0.6 and x <= 1.6 and y<-0.5 and (angle>-1.6 and angle<-1.4): #该转向时转向还没成功停进去0.4就能停但它非得提前转\r\n reward=300*(x-0.4)*(1.6-x)\r\n done=0\r\n # elif x >= 0.4 and x <= 1.6 and y<-0.5 and (angle>2): #该转向时不转向\r\n # reward=10*(1-x)\r\n # done=0\r\n elif x >= 0.4 and x <= 1.6 and (angle>-1):#转向两次没法停\r\n reward=-30\r\n done=1\r\n elif x>=0.4 and x<=1.6 and y>=-0.5 and y<=0.5 and (angle>-1.6 and angle<-1.4):#停车成功\r\n print(\"停车成功\")\r\n reward=300\r\n done=1\r\n elif x>=1.6:#越界\r\n reward=-60\r\n done=1\r\n elif collision:#碰撞\r\n reward=-50\r\n done=1\r\n else:#还能停车,再往前就不行\r\n print(\"不连续点\")\r\n return reward,bool(done)\r\n def step(self, action):\r\n if action==self.gobackward:\r\n self.car.go_backward()\r\n else:\r\n self.car.turn()\r\n observation=self.car.get_observation()\r\n collision=self.car.detect_collision()\r\n reward,done=self.compute_reward(observation,collision)\r\n info={}\r\n return observation, reward, done, info\r\n def reset(self):\r\n self.car.reset()\r\n return self.car.get_observation()\r\n\r\n def render(self, mode='human'):\r\n ...\r\n def close (self):\r\n ...\r\n\r\nenv =AutoParkEnv()\r\nmodel = DQN.load(\"train_model_distance_sensor_300000.zip\")\r\n# model = DQN(\"MultiInputPolicy\", env, verbose=1,tensorboard_log=\"./log\",learning_starts=50000)\r\n# model.learn(total_timesteps=500000, log_interval=4)#学习\r\n# model.save(\"auto5\")\r\n\r\nobs = env.reset()\r\n# model.save(\"auto4\")\r\n# model.learn(total_timesteps=100000, log_interval=4)#学习\r\n\r\nwhile True:\r\n action, _states = model.predict(obs, deterministic=True)\r\n obs, reward, done, info = env.step(action)\r\n print(\"obs\",\"reward\",\"done\",obs,reward,done)\r\n env.render()\r\n if done:\r\n obs = env.reset()\r\n","repo_name":"Jay-Humor/Reinforcement_Learning_Auto_Parking","sub_path":"Webots/controllers/rl_controller/rl_controller.py","file_name":"rl_controller.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"36277799512","text":"#!/usr/bin/env python\n\nimport mcpi.minecraft as minecraft\nimport mcpi.block as block\nimport time\nimport datetime\nimport math\nimport sys\n\n\n#mid point circle algorithm\ndef createTunnelSegment(mc, x0, y0, z, radius, blockType, torch):\n\n blockType2 = block.AIR\n blockType3 = block.AIR\n f = 1 - radius\n ddf_x = 1\n ddf_y = -2 * radius\n x = 0\n y = radius\n sleep = 0 \n sleep2 = 0 \n sideSlots = round(radius * .25)\n slotFilled = dict()\n\n #print \"Creating Tunnel, Radius:\",radius,\", sideSlots:\",sideSlots,\", torch: \",torch\n time.sleep(sleep)\n\n #print \"Set the top block\"\n mc.setBlock(x0, y0 + radius, z, blockType)\n time.sleep(sleep)\n #print \"Set the bottom block\"\n mc.setBlock(x0, y0 - radius, z, blockType)\n time.sleep(sleep)\n #print \"Set the left block\"\n mc.setBlock(x0 + radius, y0, z, blockType)\n if(torch):\n #print \"Setting a torch, x:\",x0 + radius,\", y:\",y0,\", z:\",z\n mc.setBlock(x0 + radius + 1, y0, z, blockType)\n mc.setBlock(x0 + radius, y0, z, block.TORCH, 1)\n print(\"Left Torch block data: \", mc.getBlockWithData(x0 + radius , y0, z))\n time.sleep(sleep)\n #print \"Set the right block\"\n mc.setBlock(x0 - radius, y0, z, blockType)\n if(torch):\n #print \"Setting a torch, x:\",x0 - radius,\", y:\",y0,\", z:\",z\n mc.setBlock(x0 - radius - 1, y0, z, blockType)\n mc.setBlock(x0 - radius, y0, z, block.TORCH, 2)\n print(\"Right Torch block data: \", mc.getBlockWithData(x0 - radius , y0, z))\n time.sleep(sleep)\n\n # Fill the center line\n #print \"Fill Circle Center line verticle\"\n y1 = y0 - y + 1\n y2 = y0 + y\n while y1 < y2:\n mc.setBlock(x0, y1, z, blockType2)\n y1 += 1\n time.sleep(sleep2)\n\n counter = 0\n\n while x < y:\n if f >= 0:\n y -= 1\n ddf_y += 2\n f += ddf_y\n x += 1\n ddf_x += 2\n f += ddf_x \n\n counter += 1\n\n #print \"Set the blocks to the right and left of the top blocks\"\n mc.setBlock(x0 + x, y0 + y, z, blockType)\n time.sleep(sleep)\n mc.setBlock(x0 - x, y0 + y, z, blockType)\n time.sleep(sleep)\n\n #print \"Set the blocks to the right and left of the bottom blocks\"\n mc.setBlock(x0 + x, y0 - y, z, blockType)\n time.sleep(sleep)\n mc.setBlock(x0 - x, y0 - y, z, blockType)\n time.sleep(sleep)\n if(x < radius):\n #print \"Fill Circle Loop 2\"\n y1 = y0 - y + 1\n y2 = y0 + y\n while y1 < y2:\n mc.setBlock(x0 + x, y1, z, blockType2)\n mc.setBlock(x0 - x, y1, z, blockType2)\n y1 += 1\n time.sleep(sleep2)\n\n #print \"Set the blocks above the side blocks\"\n mc.setBlock(x0 + y, y0 + x, z, blockType)\n time.sleep(sleep)\n mc.setBlock(x0 - y, y0 + x, z, blockType)\n time.sleep(sleep)\n\n #print \"Set the blocks below the side blocks\"\n mc.setBlock(x0 + y, y0 - x, z, blockType)\n time.sleep(sleep)\n mc.setBlock(x0 - y, y0 - x, z, blockType)\n time.sleep(sleep)\n #print \"y:\",y\n if(radius > y > (radius - sideSlots)):\n if((x0 + y) in slotFilled):\n #print \"slot:\",(x0 + y),\" is filled already, skip\"\n a = 1\n else:\n y1 = y0 - x + 1\n y2 = y0 + x\n #print \"Fill the side slot blocks\"\n while y1 < y2:\n mc.setBlock(x0 + y, y1, z, blockType3)\n mc.setBlock(x0 - y, y1, z, blockType3)\n y1 += 1\n time.sleep(sleep2)\n\n # Set the slot hash so you don't fill this slot again\n slotFilled[(x0 +y)] = 1\n\n#find point on circle\ndef findPointOnCircle(cx, cy, radius, angle):\n x = cx + math.sin(math.radians(angle)) * radius\n y = cy + math.cos(math.radians(angle)) * radius\n return((int(x + 0.5),int(y + 0.5)))\n\n# Create a tunnel\ndef createTunnel():\n\n mc = minecraft.Minecraft.create()\n\n # Find your position\n position = mc.player.getPos()\n\n # Now put the tunnel 10 blocks ahead on the z axis, y + radius\n radius = 3\n x = position.x\n y = position.y + radius - 1\n z = position.z + 1\n\n mc.postToChat(\"Creating a tunnel, center is: x=%s y=%s z=%s\" % (int(x), int(y), int(z)))\n print(\"Creating a tunnel, center is: x=%s y=%s z=%s\" % (int(x), int(y), int(z)))\n\n length = 0\n\n while(length < 50):\n\n length += 1\n torch = 0\n\n if(int(round(z)) % 5 == 0):\n torch = 1\n\n tunnelCenter = minecraft.Vec3(x, y, z)\n\n #z -= 1 \n z += 1 \n #radius += 1 \n\n blockType = block.OBSIDIAN\n createTunnelSegment(mc, tunnelCenter.x, tunnelCenter.y, tunnelCenter.z, radius, blockType, torch)\n\n\nif __name__ == \"__main__\":\n sys.exit(createTunnel())\n","repo_name":"jwgreene1/mimaze","sub_path":"modules/draw/tunnel.py","file_name":"tunnel.py","file_ext":"py","file_size_in_byte":4908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13377097840","text":"#!/usr/bin/python3\nimport sys\nimport configparser\nimport urllib.request\nimport os\nimport tkinter\n\n\ndef filter_num(number):\n valid_nums = ['0', '1', '2', '3', '4', '5', '6', '7', \n '8', '9', '*', '#']\n if number.upper() == 'VM':\n return ['VM']\n clean_num = []\n for l in list(number):\n if l not in valid_nums:\n print('Invalid digit')\n sys.exit(1)\n else:\n if l == '#':\n clean_num.append('HASH')\n elif l == '*':\n clean_num.append('STAR')\n else:\n clean_num.append(l)\n return clean_num\n\n\ndef parse_phone(number, send):\n clean_num = filter_num(number)\n if send:\n clean_num.append('SEND')\n return ':'.join(clean_num)\n\n\ndef get_config():\n config = configparser.ConfigParser()\n conf_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'dial_config.ini')\n conf_file = config.read(conf_path)\n\n if not conf_file:\n print('Configuration file not found, please ensure file is located in {}'.format(os.getcwd()))\n print('Ensure file is named dial_config.ini')\n sys.exit(1)\n\n dial = config['dial']\n if not dial:\n print('Improperly prepared config file dial section is not found, \\\n please check spelling')\n sys.exit(1)\n else:\n return dial\n\n\ndef send_keys(keys):\n dial = get_config()\n host = dial.get('host') or 'localhost'\n passcode = dial.get('passcode') or 'admin'\n send = dial.get('send') or 'true'\n add_send = send.lower() == 'true'\n req_header = {'Host': host,\n 'User-Agent': 'Python dial script',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate',\n 'Connection': 'keep-alive',\n 'Cookie': 'session-role=admin; session-identity=12345; TRACKID=789',\n 'Upgrade-Insecure-Requests': 1,\n 'Pragma': 'no-cache',\n 'Cache-Control': 'no-cache', }\n num = parse_phone(keys, add_send)\n req = urllib.request.Request('http://{}/cgi-bin/api-send_key?passcode={}&keys={}'.format(host, passcode, num),\n headers=req_header)\n try:\n with urllib.request.urlopen(req) as response:\n if response.status != 200:\n print('Request returned a {}:{} please check your \\\n configuration and try again.'.format(response.status,\n response.reason))\n except urllib.error.URLError:\n print('There was an error with the url that accessed. Attempted to access {}'.format(req))\n\n\ndef main():\n \"\"\"\n This takes care of sending digits to your grandstream\n phone and optionally dialing.\n \"\"\"\n if len(sys.argv) < 2:\n def get_text():\n send_keys(e1.get())\n master = tkinter.Tk()\n master.title(\"GS Dial\")\n tkinter.Label(master, text=\"Enter Phone Number\").grid(row=0)\n e1 = tkinter.Entry(master)\n e1.grid(row=0, column=1)\n tkinter.Button(master,\n text='Quit',\n command=master.quit).grid(row=3,\n column=0,\n sticky=tkinter.W,\n pady=4)\n tkinter.Button(master,\n text='Dial',\n command=get_text).grid(row=3,\n column=1,\n sticky=tkinter.W,\n pady=4)\n e1.bind('', lambda _: get_text())\n e1.bind('', lambda _: get_text())\n tkinter.mainloop()\n else:\n send_keys(sys.argv[1])\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"havoc83/grandstream_dial","sub_path":"dial.py","file_name":"dial.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28418469482","text":"\"\"\"\nAuthor: Oren Sitton\nFile: Peer Discovery Server.py\nPython Version: 3.8\nDescription: Server used by nodes to discover other nodes in the network (peer discovery)\n\"\"\"\nimport logging\nimport queue\nimport socket\nimport sys\n\nimport select\n\n\ndef initialize_server(ip, port):\n \"\"\"\n initializes server socket object to address,\n non-blocking and to accept new connections\n :param ip: ipv4 address\n :type ip: str\n :param port: tcp port\n :type port: int\n :return: initialized server socket\n :rtype: socket.socket\n \"\"\"\n\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.setblocking(False)\n server.bind((ip, port))\n server.listen(5)\n\n logging.info(\"Server initiated at address ({}, {})\"\n .format(server.getsockname()[0], server.getsockname()[1]))\n\n return server\n\n\ndef hexify(number, length):\n \"\"\"\n calculates hexadecimal value of the number, with prefix zeroes to match length\n :param number: number to calculate hex value for, in base 10\n :type number: int\n :param length: requested length of hexadecimal value\n :type length: int\n :return: hexadecimal value of the number, with prefix zeroes\n :rtype: str\n :raise Exception: ValueError (message size is larger than length)\n \"\"\"\n if not isinstance(number, int):\n raise TypeError(\"Transaction.hexify(number, length): expected number to be of type int\")\n if not isinstance(length, int):\n raise TypeError(\"Transaction.hexify(number, length): expected length to be of type int\")\n if number < 0:\n raise ValueError(\"Transaction.hexify(number, length): expected non-negative value for number, received {} \"\n \"instead\".format(number))\n if length < 0:\n raise ValueError(\"Transaction.hexify(number, length): expected non-negative value for length, received {} \"\n \"instead\".format(length))\n\n hex_base = hex(number)[2:]\n\n if len(hex_base) <= length:\n hex_base = (length - len(hex_base)) * \"0\" + hex_base\n return hex_base\n else:\n raise ValueError(\"Transaction.hexify(number, length): message size is larger than length\")\n\n\ndef handle_message(request, ip_addresses, destination):\n \"\"\"\n handles incoming messages from clients. Analyzes client request and creates appropriate response.\n :param request: message received from client\n :type request: str\n :param ip_addresses: current stored addresses of nodes in the network\n :type ip_addresses: list\n :param destination: address of the client who sent the request\n :type destination: str\n :return: reply to send to client\n :rtype: str\n \"\"\"\n ip_addresses = ip_addresses.copy()\n request_type = request[:1]\n\n if request_type == \"a\":\n if destination in ip_addresses and ip_addresses[len(ip_addresses) - 1] != destination:\n ip_addresses[ip_addresses.index(destination)] = ip_addresses[len(ip_addresses) - 1]\n # replace requester's address with a different address\n\n peer_count = 0\n reply = \"\"\n\n for x in ip_addresses[:-1]:\n if x != \"\":\n peer_count += 1\n if x == \"localhost\":\n reply += \"{}{}{}{}\".format(hexify(127, 2), hexify(0, 2), hexify(0, 2), hexify(1, 2))\n else:\n x = x.split(\".\")\n reply += \"{}{}{}{}\".format(\n hexify(int(x[0]), 2), hexify(int(x[1]), 2), hexify(int(x[2]), 2), hexify(int(x[3]), 2))\n\n reply = \"b{}{}\".format(hexify(peer_count, 2), reply)\n\n else:\n reply = \"f{}\".format(\"unrecognized request\".encode(\"utf-8\").hex())\n\n length = hexify(len(reply), 5)\n\n reply = \"{}{}\".format(length, reply)\n\n return reply\n\n\ndef main():\n if len(sys.argv) != 3:\n raise RuntimeError(\"Peer Discovery Server requires exactly 2 arguments\")\n\n ip = \"0.0.0.0\"\n port = int(sys.argv[1])\n\n # maximum amount of addresses server will send nodes\n addresses_amount = 3\n\n # list to store node addresses\n ip_addresses = []\n\n # amount of ip addresses currently stored\n count = int(sys.argv[2])\n for x in range(addresses_amount + 1):\n ip_addresses.append(\"\")\n\n server_socket = initialize_server(ip, port)\n\n # lists of sockets to listen to\n inputs = [server_socket]\n outputs = []\n\n # lists of messages to send to clients\n message_queues = {}\n\n while inputs:\n readable, writable, exceptional = select.select(inputs, outputs, inputs)\n\n for sock in readable:\n if sock is server_socket:\n connection, client_address = server_socket.accept()\n connection.setblocking(False)\n inputs.append(connection)\n\n logging.info(\"Connected to client at ({}, {})\"\n .format(client_address[0], client_address[1]))\n\n if client_address[0] not in ip_addresses:\n ip_addresses[count] = client_address[0]\n count += 1\n count %= addresses_amount + 1\n\n else:\n try:\n data = sock.recv(5).decode()\n if data:\n logging.info(\"Received message from client at ({}, {})\"\n .format(sock.getpeername()[0], sock.getpeername()[1]))\n data = sock.recv(int(data, 16)).decode()\n if sock in message_queues:\n message_queues[sock].put(data)\n else:\n message_queues[sock] = queue.Queue()\n message_queues[sock].put(data)\n\n if sock not in outputs:\n outputs.append(sock)\n\n else:\n logging.info(\"Disconnected from client at ({}, {})\"\n .format(sock.getpeername()[0], sock.getpeername()[1]))\n\n if sock in outputs:\n outputs.remove(sock)\n inputs.remove(sock)\n sock.close()\n if sock in message_queues:\n del message_queues[sock]\n\n except ConnectionResetError:\n logging.info(\"An existing connection was forcibly closed by the client: ({}, {})\"\n .format(sock.getpeername()[0], sock.getpeername()[1]))\n\n if sock in outputs:\n outputs.remove(sock)\n inputs.remove(sock)\n sock.close()\n if sock in message_queues:\n del message_queues[sock]\n\n for sock in writable:\n if not message_queues[sock].empty():\n next_msg = message_queues[sock].get()\n reply = handle_message(next_msg, ip_addresses, sock.getpeername()[0])\n sock.send(reply.encode())\n logging.info(\"Sent message to client at ({}, {})\"\n .format(sock.getpeername()[0], sock.getpeername()[1]))\n\n if message_queues[sock].empty():\n del message_queues[sock]\n outputs.remove(sock)\n\n for sock in exceptional:\n inputs.remove(sock)\n if sock in outputs:\n outputs.remove(sock)\n sock.close()\n del message_queues[sock]\n logging.info(\"Disconnected from client at ({}, {})\"\n .format(sock.getpeername()[0], sock.getpeername()[1]))\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO, format=\"%(asctime)s: %(message)s\")\n main()\n","repo_name":"OrenSitton/PeerDiscoveryServer","sub_path":"PeerDiscoveryServer.py","file_name":"PeerDiscoveryServer.py","file_ext":"py","file_size_in_byte":7791,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"4693705131","text":"# https://github.com/pydata/xarray/issues/501#issuecomment-126461466 \n\nimport geopandas\nfrom rasterio import features\nfrom affine import Affine\n\ndef transform_from_latlon(lat, lon):\n lat = np.asarray(lat)\n lon = np.asarray(lon)\n trans = Affine.translation(lon[0], lat[0])\n scale = Affine.scale(lon[1] - lon[0], lat[1] - lat[0])\n return trans * scale\n\ndef rasterize(shapes, coords, fill=np.nan, **kwargs):\n \"\"\"Rasterize a list of (geometry, fill_value) tuples onto the given\n xray coordinates. This only works for 1d latitude and longitude\n arrays.\n \"\"\"\n transform = transform_from_latlon(coords['latitude'], coords['longitude'])\n out_shape = (len(coords['latitude']), len(coords['longitude']))\n raster = features.rasterize(shapes, out_shape=out_shape,\n fill=fill, transform=transform,\n dtype=float, **kwargs)\n return xray.DataArray(raster, coords=coords, dims=('latitude', 'longitude'))","repo_name":"story645/team","sub_path":"paper/figcode/geomask.py","file_name":"geomask.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"16074000378","text":"\"\"\"Лабораторная работа №2. Вариант 14.\n\nМолофеев Иван. Группа ИСТбд-21.\n\nВычислить сумму знакопеременного ряда -(|х(3n-1)|)/(3n-1)!, где х-матрица ранга к (к и матрица задаются случайным образом),\nn - номер слагаемого. Сумма считается вычисленной, если точность вычислений будет не меньше t знаков после запятой.\nУ алгоритма д.б. линейная сложность. Операция умножения –поэлементная.\"\"\"\n\nimport random\nimport numpy as np\n\n\ndef matrix(M, matr_name):\n print(\"Матрица \" + matr_name)\n for i in M: # перебор всех строк матрицы\n for j in i: # перебор всех элементов в строке\n print(\"%5d\" % j, end=' ')\n print()\n\n\nrandomFill = random.randint(1, 10)\nx = np.zeros((randomFill, randomFill), int)\na = np.zeros((randomFill, randomFill), dtype=float)\nsum = 0\nfor i in range(randomFill):\n for j in range(randomFill):\n x[i][j] = np.random.randint(1, 10)\nmatrix(x, \"x:\") # выводим матрицу\n\nt = int(input(\"\\nВведите количество знаков после запятой п��и вычислении неточности: \\n\"))\nt1 = 0.1 ** t\n\nnumber = 1\nmodl = 1\nfactorial = 1\ndeterminant = 0\ndifference = 1\nns = 0\nwhile abs(difference) > t1:\n ns += sum\n number += 1\n temp = (3 * number) - 1\n factorial = np.math.factorial(temp)\n modl = - np.linalg.matrix_power(x, temp)\n determinant = np.linalg.det(modl)\n sum = sum + (determinant/factorial)\n difference = abs(ns - sum) # проверка точности вычислений\n ns = 0\n print(number - 1, ':', sum, ' ', difference)\nprint('Сумма знакопеременного ряда:', sum, '\\nТочность:', t)","repo_name":"Mizless/lab2_2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28013301681","text":"from urllib.parse import urlencode\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, HttpResponseBadRequest\nfrom django.shortcuts import get_object_or_404, render\nfrom django.views.generic import DetailView, ListView\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom peacecorps.forms import DonationAmountForm, DonationPaymentForm\nfrom peacecorps.models import (\n Account, Campaign, FAQ, FeaturedCampaign, FeaturedProjectFrontPage,\n Issue, Project, Vignette)\nfrom peacecorps.payxml import convert_to_paygov\n\n\ndef donation_payment(request):\n \"\"\" Collect donor contact information. \"\"\"\n\n amount = request.GET.get('amount')\n if amount is None:\n return HttpResponseBadRequest('amount must be provided.')\n elif not amount.isdigit():\n return HttpResponseBadRequest('amount must be an integer value')\n else:\n amount = int(amount)\n\n project_code = request.GET.get('project')\n if project_code is None:\n return HttpResponseBadRequest('project must be provided.')\n account = Account.objects.filter(code=project_code).first()\n if not account:\n return HttpResponseBadRequest('Invalid project')\n project = account.project_set.first()\n\n context = {\n 'amount': amount,\n 'project_code': project_code,\n 'project': project,\n 'account_name': account.name,\n 'agency_id': settings.PAY_GOV_AGENCY_ID,\n 'app_name': settings.PAY_GOV_APP_NAME,\n 'oci_servlet_url': settings.PAY_GOV_OCI_URL,\n }\n\n if request.method == 'POST':\n form = DonationPaymentForm(request.POST)\n else:\n data = {'payment_amount': amount, 'project_code': project_code}\n form = DonationPaymentForm(initial=data)\n context['form'] = form\n\n if form.is_valid() and request.POST.get('force_form') != 'true':\n data = {k: v for k, v in form.cleaned_data.items()}\n paygov = convert_to_paygov(\n data, account, \"https://\" + request.get_host())\n paygov.save()\n context['data'] = data\n context['agency_tracking_id'] = paygov.agency_tracking_id\n return render(request, 'donations/checkout_review.jinja', context)\n else:\n return render(request, 'donations/checkout_form.jinja', context)\n\n\ndef donate_landing(request):\n \"\"\"First page for the donations section\"\"\"\n featuredprojects = list(map(\n lambda fp: fp.project,\n FeaturedProjectFrontPage.objects.select_related(\n 'project__featured_image')))\n projects = Project.published_objects.select_related('country', 'account')\n\n try:\n featuredcampaign = FeaturedCampaign.objects.get(id=1).campaign\n except FeaturedCampaign.DoesNotExist:\n featuredcampaign = None\n\n return render(\n request,\n 'donations/donate_landing.jinja',\n {\n 'title': 'Donate',\n 'top_vignette': Vignette.for_slug('donate_landing_top'),\n 'bottom_vignette': Vignette.for_slug('donate_landing_bottom'),\n 'featuredcampaign': featuredcampaign,\n 'sectors': Campaign.objects.filter(\n campaigntype=Campaign.SECTOR).order_by('name'),\n 'featuredprojects': featuredprojects,\n 'projects': projects,\n })\n\n\ndef donate_project(request, slug):\n \"\"\"A profile for each project. Also includes a donation form\"\"\"\n project = get_object_or_404(\n Project.published_objects.select_related(\n 'volunteerpicture', 'featured_image', 'account', 'overflow'),\n slug=slug)\n if request.method == 'POST':\n form = DonationAmountForm(data=request.POST)\n if form.is_valid():\n if project.account.funded() and project.overflow:\n code = project.overflow.code\n else:\n code = project.account.code\n params = {'project': code,\n # convert back into cents\n 'amount': int(round(\n form.cleaned_data['payment_amount'] * 100))}\n return HttpResponseRedirect(\n reverse('donations_payment') + '?' + urlencode(params))\n else:\n form = DonationAmountForm()\n\n return render(\n request,\n 'donations/donate_project.jinja',\n {\n 'title': project.title,\n 'project': project,\n 'account': project.account,\n 'donate_form': form,\n \"IS_PROJECT\": project.account.category == Account.PROJECT,\n })\n\n\ndef donate_projects_funds(request):\n \"\"\"\n The page that displays a sorter for all projects, issues, volunteers.\n \"\"\"\n countries = Campaign.objects.filter(\n campaigntype=Campaign.COUNTRY).order_by('name')\n issues = Issue.objects.all().order_by('name')\n projects = Project.published_objects.select_related(\n 'country', 'account').order_by('volunteername')\n\n return render(\n request,\n 'donations/donate_all.jinja',\n {\n 'countries': countries,\n 'issues': issues,\n 'projects': projects,\n })\n\n\ndef special_funds(request):\n \"\"\"Contains general, global, and memorial funds\"\"\"\n general_funds = Campaign.objects.filter(\n campaigntype=Campaign.GENERAL).order_by('pk')\n memorial_funds = Campaign.objects.filter(campaigntype=Campaign.MEMORIAL)\n # Quick hack to pull out the volunteer's name. Replace when we have a new\n # model\n for fund in memorial_funds:\n if fund.name.endswith('Memorial Fund'):\n fund.memorial_name = fund.name[:-len(\"Memorial Fund\")].strip()\n else:\n fund.memorial_name = fund.name.strip()\n name_parts = fund.memorial_name.split(' ')\n fund.sort_name = \" \".join(name_parts[-1:] + name_parts[:-1])\n memorial_funds = sorted(memorial_funds, key=lambda f: f.sort_name)\n return render(request, \"donations/special_funds.jinja\", {\n \"general_funds\": general_funds, \"memorial_funds\": memorial_funds})\n\n\ndef fund_detail(request, slug):\n campaign = get_object_or_404(Campaign.objects.select_related('account'),\n slug=slug)\n if request.method == \"POST\":\n form = DonationAmountForm(data=request.POST)\n if form.is_valid():\n params = {'project': campaign.account.code,\n # convert back into cents\n 'amount': int(round(\n form.cleaned_data['payment_amount'] * 100))}\n return HttpResponseRedirect(\n reverse('donations_payment') + '?' + urlencode(params))\n else:\n form = DonationAmountForm()\n\n return render(\n request,\n 'donations/fund_detail.jinja',\n {\n 'campaign': campaign,\n 'account': campaign.account,\n 'donate_form': form,\n \"IS_PROJECT\": campaign.account.category == Account.PROJECT,\n })\n\n\n@csrf_exempt\ndef failure(request, slug, redirect_to):\n return HttpResponseRedirect(reverse(redirect_to, kwargs={'slug': slug})\n + '?payment_status=failed')\n\n\nclass AbstractReturn(DetailView):\n \"\"\"Shared by views related to users returning from pay.gov. This includes\n success pages for projects/funds\"\"\"\n def post(self, request, *args, **kwargs):\n path = request.path\n params = request.GET.urlencode()\n if params:\n path += \"?\" + params\n return HttpResponseRedirect(path)\n\n @csrf_exempt\n def dispatch(self, *args, **kwargs):\n return super(AbstractReturn, self).dispatch(*args, **kwargs)\n\n def get_context_data(self, **kwargs):\n \"\"\"Must add sharing link info\"\"\"\n context = super(AbstractReturn, self).get_context_data(**kwargs)\n path = self.request.scheme + \"://\" + self.request.get_host()\n path += reverse(\"donate \" +\n self.get_context_object_name(context['object']),\n kwargs={'slug': context['object'].slug})\n context['share_url'] = path\n context['share_text'] = settings.SHARE_TEMPLATE % path\n context['share_subject'] = settings.SHARE_SUBJECT\n return context\n\n\nclass ProjectReturn(AbstractReturn):\n queryset = Project.objects.select_related(\n 'account', 'country', 'featured_image', 'overflow',\n 'volunteerpicture')\n\n\nclass CampaignReturn(AbstractReturn):\n queryset = Campaign.objects.select_related('account', 'featured_image')\n\n\nclass FAQs(ListView):\n model = FAQ\n template_name = 'donations/faq.jinja'\n","repo_name":"annalee/peacecorps-site","sub_path":"peacecorps/peacecorps/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"85"} +{"seq_id":"20972788966","text":"import tweepy\nfrom textblob import TextBlob\nimport pandas as pd\nimport psycopg2\nimport time\nclass UtlrastalkerTwitter():\n def __init__(self):\n self.consumer_key = ''\n self.consumer_secret = ''\n self.acces_token = ''\n self.acces_token_secret = ''\n self.auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)\n self.auth.set_access_token(self.acces_token, self.acces_token_secret)\n self.api = tweepy.API(self.auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)\n\n def generic_search(self, item_to_search):\n self.public_tweets = self.api.search('item_to_search')\n self.sentiment = []\n self.public_tweets1 = []\n print(self.public_tweets)\n for tweet in self.public_tweets:\n print(tweet.text)\n\n self.analysis = TextBlob(str(self.tweet.text))\n self.analysis.translate(from_lang='es' , to='en')\n print(analysis.sentiment,\"analisis\")\n self.public_tweets1.append(self.weet.text)\n self.sentiment.append(self.analysis.sentiment)\n\n self.data = {'sentiments': self.sentiment, 'twitts': self.public_tweets1}\n\n def user_search(self, usr):\n self.user = self.api.get_user(str(usr))\n\n\n\n print('usuario : ',self.user.screen_name)\n print('Cant-Seguidores : ',self.user.followers_count)\n self.locacion_pos_followers = []\n self.name_followers = []\n self.screen_name = []\n for us in tweepy.Cursor(self.api.followers, id=usr, count=30).items():\n #self.page_count += 1\n #print ('Getting page {} for followers'.format(self.page_count))\n if us.location == '' :\n us.location='N/A'\n if us.name =='':\n us.name ='N/A'\n print(us.location ,'\\t',us.name,',',us.screen_name)\n self.locacion_pos_followers.append(us.name)\n self.name_followers.append(us.location)\n self.screen_name.append(us.screen_name)\n\n\n self.timeline = self.api.user_timeline\n\n\n\n\n cursor = tweepy.Cursor(self.timeline,id=usr)\n self.timeline = []\n self.sentiment= []\n self._=0\n for i in cursor.items(limit=self.user.followers_count):\n\n self.analysis = TextBlob(i.text)\n self.timeline.append(i.text)\n try:\n if self.analysis.detect_language() != 'en' :\n self.analysis= self.analysis.translate(from_lang=self.analysis.detect_language(), to='en' )\n self.sentiment.append(self.analysis.sentiment)\n else:\n self.sentiment.append(self.analysis.sentiment)\n except Exception as e:\n self.sentiment.append(e)\n if i.text == '' :\n self.timeline.append('N/A')\n self.sentiment.append('N/A')\n continue\n print(self.sentiment[self._],i.text)\n #self.timeline.append(i.text)\n #self.sentiment.append(self.analysis.sentiment)\n self._ += 1\n self.dffollowers = pd.DataFrame(\n {'Followers.name' : self.name_followers,\n 'followers.screen_name': self.screen_name,\n 'Followers.Loc' : self.locacion_pos_followers,\n\n })\n print(len(self.timeline))\n print(len(self.sentiment))\n self.dftimeline = pd.DataFrame({\n 'timeline_twits': self.timeline,\n 'timeline.sentiment.twitts': self.sentiment,\n \t})\n print(self.dffollowers.head(10))\n print(self.dftimeline.head(10))\n self.dftimeline.to_csv(usr+'_timeline'+'.csv')\n self.dffollowers.to_csv(usr+'_followers'+'.csv')\n return\n\n\ndec = True\nwhile dec:\n\n\tprint(\"\"\"\n\n\t █ ██ ██▓ ▄▄▄█████▓ ██▀███ ▄▄▄ \n\t ██ ▓██▒▓██▒ ▓ ██▒ ▓▒▓██ ▒ ██▒▒████▄ \n\t▓██ ▒██░▒██░ ▒ ▓██░ ▒░▓██ ░▄█ ▒▒██ ▀█▄ \n\t▓▓█ ░██░▒██░ ░ ▓██▓ ░ ▒██▀▀█▄ ░██▄▄▄▄██ \n\t▒▒█████▓ ░██████▒▒██▒ ░ ░██▓ ▒██▒ ▓█ ▓██▒ \n\t░▒▓▒ ▒ ▒ ░ ▒░▓ ░▒ ░░ ░ ▒▓ ░▒▓░ ▒▒ ▓▒█░ \n\t░░▒░ ░ ░ ░ ░ ▒ ░ ░ ░▒ ░ ▒░ ▒ ▒▒ ░ \n\t ░░░ ░ ░ ░ ░ ░ ░░ ░ ░ ▒ \n\t ░ ░ ░ ░ ░ ░ \n\t \n\t ██████ ▄▄▄█████▓ ▄▄▄ ██▓ ██ ▄█▀▓█████ ██▀███ \n\t▒██ ▒ ▓ ██▒ ▓▒▒████▄ ▓██▒ ██▄█▒ ▓█ ▀ ▓██ ▒ ██▒\n\t░ ▓██▄ ▒ ▓���█░ ▒░▒██ ▀█▄ ▒██░ ▓███▄░ ▒███ ▓██ ░▄█ ▒\n\t ▒ ██▒░ ▓██▓ ░ ░██▄▄▄▄██ ▒██░ ▓██ █▄ ▒▓█ ▄ ▒██▀▀█▄ \n\t▒██████▒▒ ▒██▒ ░ ▓█ ▓██▒░██████▒▒██▒ █▄░▒████▒░██▓ ▒██▒\n\t▒ ▒▓▒ ▒ ░ ▒ ░░ ▒▒ ▓▒█░░ ▒░▓ ░▒ ▒▒ ▓▒░░ ▒░ ░░ ▒▓ ░▒▓░\n\t░ ░▒ ░ ░ ░ ▒ ▒▒ ░░ ░ ▒ ░░ ░▒ ▒░ ░ ░ ░ ░▒ ░ ▒░\n\t░ ░ ░ ░ ░ ▒ ░ ░ ░ ░░ ░ ░ ░░ ░ \n\t ░ ░ ░ ░ ░░ ░ ░ ░ ░ \n\t \n\n\t v0.0.0.1\n\t TR4NS1STH0R\n\t\"\"\")\n\tobjeto = UtlrastalkerTwitter()\n\n\tprint('busqueda por usuario o en general ')\n\tprint('gen : general \\t usr : usuario')\n\tdec= str(input('>> '))\n\tif dec == 'gen' :\n\t\tobjeto.generic_search(input('introduce el twitt'))\n\tif dec == 'usr':\n\t\tobjeto.user_search(input('introduce el usuario'))\n\t\n\tif dec == 'cancel':\n\t\tdec=False\n\t\tbreak\n","repo_name":"morwen1/ultrastalker","sub_path":"ultrastalker_twitter.py","file_name":"ultrastalker_twitter.py","file_ext":"py","file_size_in_byte":6414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23071284795","text":"import turtle as tr\n\n\ntr.shape('turtle')\n\ndef draw_number(n):\n if n == '0':\n for line in zero:\n eval(line.rstrip()) \n elif n == '1':\n for line in one:\n eval(line.rstrip()) \n elif n == '4':\n for line in four:\n eval(line.rstrip())\n elif n == '7':\n for line in seven:\n eval(line.rstrip())\n else:\n print('nope')\n\nwith open('0.txt') as file:\n zero = file.readlines()\nwith open('1.txt') as file:\n one = file.readlines() \nwith open('4.txt') as file:\n four = file.readlines()\nwith open('7.txt') as file:\n seven = file.readlines()\n \ntr.penup()\ntr.goto(-350, 300)\ntr.pendown() \n\nnums = list('141700')\nfor x in nums:\n tr.pendown() \n draw_number(x)\n tr.penup() \n tr.forward(60)\n","repo_name":"lolicoder/python2021FOPF","sub_path":"lesson3/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21206794753","text":"# 21codons.py\n\n# Nikki Moreno\n# 4 February 2023\n# MCB 185\n\n### Purpose ###\n# Print out all the codons for the sequence below in reading frame 1\n# Hint: use the slice operator\n\ndna = 'ATAGCGAATATCTCTCATGAGAGGGAA'\n\nfor ORF_1 in range(0, len(dna), 3): # establish ORF and step length\n\tcodon = dna[ORF_1: ORF_1 + 3] # codon defined by slice\n\tprint(codon)\nprint() # new line after every step\n\n\"\"\"\npython3 21codons.py\nATA\nGCG\nAAT\nATC\nTCT\nCAT\nGAG\nAGG\nGAA\n\"\"\"\n","repo_name":"nikki-moreno/homework","sub_path":"21codons.py","file_name":"21codons.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"574734162","text":"import time\n\nfrom django.db import transaction\nfrom django.utils import timezone\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.exceptions import NotFound\nfrom rest_framework.exceptions import NotAuthenticated\nfrom rest_framework.exceptions import ParseError\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.status import HTTP_204_NO_CONTENT\nfrom rest_framework.status import HTTP_400_BAD_REQUEST\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\n\nfrom .models import Room\nfrom .models import Amenity\nfrom .serializers import AmenitySerializer\nfrom .serializers import RoomListSerializer\nfrom .serializers import RoomDetailsSerializer\n\nfrom bookings.models import Booking\nfrom bookings.serializers import PublicBookingSerializer\nfrom bookings.serializers import CreateRoomBookingSerializer\nfrom categories.models import Category\nfrom medias.serializers import PhotoSerializer\nfrom reviews.serializers import ReviewSerializer\n\nfrom google_cloud_storage import gcs\n\n\nclass Amenities(APIView):\n def get(self, request):\n all_amenities = Amenity.objects.all()\n serializer = AmenitySerializer(all_amenities, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n serializer = AmenitySerializer(data=request.data)\n if serializer.is_valid():\n amenity = serializer.save()\n return Response(\n AmenitySerializer(amenity).data,\n )\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\nclass AmenityDetail(APIView):\n def get_object(self, pk):\n try:\n return Amenity.objects.get(pk=pk)\n except Amenity.DoesNotExist:\n raise NotFound\n\n def get(self, request, pk):\n amenitry = self.get_object(pk)\n serializer = AmenitySerializer(amenitry)\n\n return Response(\n serializer.data,\n )\n\n def put(self, request, pk):\n amenitry = self.get_object(pk)\n serializer = AmenitySerializer(\n amenitry,\n data=request.data,\n partial=True,\n )\n\n if serializer.is_valid():\n update_amenity = serializer.save()\n return Response(\n AmenitySerializer(update_amenity).data,\n )\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk):\n amenitry = self.get_object(pk)\n amenitry.delete()\n return Response(status=HTTP_204_NO_CONTENT)\n\n\nclass Rooms(APIView):\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def get(self, request):\n all_rooms = Room.objects.all()\n serializer = RoomListSerializer(\n all_rooms,\n many=True,\n context={\"request\": request},\n )\n return Response(serializer.data)\n\n def post(self, request):\n serializer = RoomDetailsSerializer(data=request.data)\n if serializer.is_valid():\n category_pk = request.data.get(\"category\")\n if not category_pk:\n raise ParseError(\"Category is required.\")\n\n try:\n category = Category.objects.get(pk=category_pk)\n if category.kind == Category.CategoryKindOption.EXPERIENCES:\n raise ParseError(\"Category kind is should be rooms.\")\n except Category.DoesNotExist:\n raise ParseError(\"Category not exist.\")\n\n try:\n with transaction.atomic():\n room = serializer.save(\n owner=request.user,\n category=category,\n )\n\n # amenities = request.data.get(\"amenities\")\n amenities = request.data.get(\"amenity\")\n\n for amenity_pk in amenities:\n amenity = Amenity.objects.get(pk=amenity_pk)\n room.amenity.add(amenity)\n\n serializer = RoomDetailsSerializer(\n room,\n context={\"request\": request},\n )\n\n return Response(serializer.data)\n except Exception as e:\n print(e)\n raise ParseError(\"Amenity not found.\")\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\nclass RoomDetail(APIView):\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n\n def get(self, request, pk):\n # time.sleep(10)\n room = self.get_object(pk)\n serializer = RoomDetailsSerializer(\n room,\n context={\"request\": request},\n )\n return Response(serializer.data)\n\n def put(self, request, pk):\n print(\"call put request\")\n print(pk)\n print(request.data.get(\"name\"))\n print(request.data.get(\"country\"))\n print(request.data)\n print(type(request.data))\n for k in request.data.keys():\n print(f\"key: {k}\")\n print(request.data[k])\n\n room = self.get_object(pk)\n\n if request.user != room.owner:\n raise PermissionDenied\n\n serializer = RoomDetailsSerializer(\n room,\n data=request.data,\n partial=True,\n )\n if serializer.is_valid():\n category_pk = request.data.get(\"category\")\n\n if not category_pk:\n raise ParseError(\"Category is required.\")\n\n try:\n category = Category.objects.get(pk=category_pk)\n if category.kind == Category.CategoryKindOption.EXPERIENCES:\n raise ParseError(\"Category kind is should be rooms.\")\n except Category.DoesNotExist:\n raise ParseError(\"Category not exist.\")\n\n try:\n with transaction.atomic():\n room = serializer.save(\n owner=request.user,\n category=category,\n )\n amenities = request.data.get(\"amenity\")\n for amenity_pk in amenities:\n amenity = Amenity.objects.get(pk=amenity_pk)\n room.amenity.add(amenity)\n\n serializer = RoomDetailsSerializer(room)\n return Response(serializer.data)\n except Exception:\n raise ParseError(\"Amenity not found.\")\n\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk):\n room = self.get_object(pk)\n\n if request.user != room.owner:\n raise PermissionDenied\n room.delete()\n return Response(status=HTTP_204_NO_CONTENT)\n\n\nclass RoomReviews(APIView):\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n\n def get(self, request, pk):\n # time.sleep(10)\n room = self.get_object(pk)\n try:\n page = int(request.query_params.get(\"page\", 1))\n except ValueError:\n page = 1\n\n item = 5\n start = (page - 1) * item\n converter = ReviewSerializer(\n room.review_set.all()[start : start + item],\n many=True,\n )\n return Response(converter.data)\n\n def post(self, request, pk):\n serializer = ReviewSerializer(data=request.data)\n if serializer.is_valid():\n review = serializer.save(\n room=self.get_object(pk),\n user=request.user,\n )\n serializer = ReviewSerializer(review)\n return Response(serializer.data)\n else:\n raise NotFound\n\n\nclass RoomAmenites(APIView):\n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n\n def get(self, request, pk):\n room = self.get_object(pk)\n try:\n page = int(request.query_params.get(\"page\", 1))\n except ValueError:\n page = 1\n\n item = 5\n start = (page - 1) * item\n converter = AmenitySerializer(\n room.amenity.all()[start : start + item],\n many=True,\n )\n return Response(converter.data)\n\n\nclass RoomPhotos(APIView):\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n\n def post(self, request, pk):\n print(\"run post request\")\n\n room = self.get_object(pk)\n\n if room.owner != request.user:\n raise PermissionDenied\n\n serializer = PhotoSerializer(data=request.data)\n if serializer.is_valid():\n photo = serializer.save(room=room)\n serializer = PhotoSerializer(photo)\n return Response(serializer.data)\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\nclass RoomBookings(APIView):\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n\n def get(self, request, pk):\n now = timezone.now()\n local_time = timezone.localtime(now).date()\n\n room = self.get_object(pk)\n bookings = Booking.objects.filter(\n room=room,\n category=Booking.BookingOption.ROOM,\n check_in_date__gt=local_time,\n )\n serializer = PublicBookingSerializer(\n bookings,\n many=True,\n )\n return Response(serializer.data)\n\n def post(self, request, pk):\n room = self.get_object(pk)\n serializer = CreateRoomBookingSerializer(\n data=request.data,\n context={\"room\": room},\n )\n\n if serializer.is_valid():\n booking = serializer.save(\n room=room,\n user=request.user,\n category=Booking.BookingOption.ROOM,\n )\n serializer = PublicBookingSerializer(booking)\n return Response(serializer.data)\n\n else:\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\nclass RoomBookingCheck(APIView):\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def get_object(self, pk):\n try:\n return Room.objects.get(pk=pk)\n except Room.DoesNotExist:\n raise NotFound\n\n def get(self, request, pk):\n room = self.get_object(pk)\n check_out_date = request.query_params.get(\"check_in_date\")\n check_in_date = request.query_params.get(\"check_out_date\")\n\n exist = Booking.objects.filter(\n room=room,\n check_in_date__lte=check_out_date,\n check_out_date__gte=check_in_date,\n ).exists()\n\n if exist:\n return Response({\"ok\": False})\n return Response({\"ok\": True})\n\n\n\"\"\"\n\n{\n \"address\": \"Seoul, South Korea\",\n \"amenity\": [6],\n \"category\": 5,\n \"city\": \"Seoul\",\n \"country\": \"South Korea\",\n \"description\": \"- Beautiful picturesque landscape view\\n - Fully furnished studio with a huge window\\n Located in the center of Seoul, our studio give…\",\n \"kind\": \"entire_place\",\n \"name\": \"Namsan tower suite_loft with two floors_45㎡\",\n \"pet_allow\": false,\n \"price\": 142000,\n \"rooms\": 3,\n \"toilets\": 123\n}\n\n\"\"\"\n\n\ndef make_error(request):\n division_by_zero = 1 / 0\n","repo_name":"jh0152park/Django_AirBnB","sub_path":"rooms/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":"85"} +{"seq_id":"27732592109","text":"import random as rand\nimport urllib2\nimport re\nimport copy as cp\nimport numpy as np \nimport matplotlib.pyplot as plt\n\nfreq=40\nplt.figure\n \n#create data\nx_series = [5,9,12,15,18,21]\n\ny_series_1 = [x**2 for x in x_series]\ny_series_3 = [x for x in x_series]\ny_series_2 = [x for x in x_series]\n\nmi,ma=min(y_series_1[0],y_series_2[0]),max(y_series_1[len(y_series_1)-1],y_series_2[len(y_series_2)-1])\n\n#plot data\nplt.plot( x_series , y_series_1 , label=\"approximate solution\" )\nplt.plot( x_series , y_series_2 , label=\"LP solution\" )\n\nplt.xlabel(\"number of Vms\" , fontsize=25 )\nplt.ylabel(\"host active at this stage\",fontsize=25)\nplt.title(\"\",fontsize=25)\n \n#add limits to the x and y axis\nplt.xlim(x_series[0]-1, x_series[len(x_series)-1]+1)\nplt.ylim(mi, ma) \n \n#create legend\nplt.legend(loc=\"upper right\")\n \n#save figure to png\n# plt.savefig(\"example.png\")\nplt.show()\n","repo_name":"devanshdalal/Sceduling-policies","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"70933230358","text":"\nimport os\nimport numpy as np\nimport pandas as pd\nfrom astropy.io import fits\nimport extinction\n\n\nclass BoxImage ( dict ):\n @property \n def array ( self ):\n return np.array( [self[key] for key in self.keys() ] )\n \n def __setitem__(self, __key, __value):\n setattr(self, __key, __value)\n return super().__setitem__(__key, __value)\n \n \n \nclass FilterCurve ( object ):\n def __init__ ( self, name, transmission, filter_type ):\n self.name = name\n self.transmission = transmission\n self.filter_type = filter_type\n\n @property\n def lambda_mean ( self ):\n filt = self.transmission\n top = np.trapz(filt[:,1]*filt[:,0], filt[:,0])\n bot = np.trapz(filt[:,1], filt[:,0])\n return top/bot\n\n def interpolate_to_wv ( self, wv ):\n filt = self.transmission\n fintp = np.interp(wv, filt[:,0], filt[:,1])\n fintp[(wvfilt[-1,0])] = 0.\n return fintp\n \nclass FilterBase ( object ):\n def load_filtercurves ( self,\n fnames=['FUV','NUV'],#,'g','r','i','z','y'], #'FUV','NUV',\n fpaths=['GALEX_GALEX.FUV.dat','GALEX_GALEX.NUV.dat'],\n #fpaths=['GALEX.FUV','GALEX.NUV','HSC-g.txt','HSC-r2.txt',\n # 'HSC-i2.txt','HSC-z.txt','HSC-Y.txt'], # 'GALEX.FUV','GALEX.NUV',\n ftype=None, # 'photon','photon',\n #is_global=[True,True,False,False,False,False],\n prefix_path='../data/filter_curves/'):\n filter_d = {}\n for ix,(name,path) in enumerate(zip(fnames,fpaths)):\n trans = np.genfromtxt(f'{prefix_path}/{path}')\n if ftype is None:\n qf = 'photon'\n else:\n qf = ftype[ix]\n filter_d[name] = FilterCurve ( name, trans, qf )\n self.filter_curves = filter_d \n self.bands = fnames\n\n\nclass MultiBandImage (object):\n def __init__ ( self, bands, zpt, pixscale ):\n self.bands = bands\n if isinstance(zpt, float):\n self.zpt = np.ones(len(bands))*zpt\n else:\n self.zpt = np.asarray(zpt)\n self.pixscale = pixscale\n self.image = BoxImage ()\n self.variance = BoxImage ()\n self.mask = BoxImage ()\n self.wcs = {}\n \n def sky2pix ( self, ra, dec, bandpass):\n coord = np.array([ra,dec]).reshape(1,2)\n cwcs = self.wcs[bandpass]\n pixcoord = cwcs.all_world2pix ( coord, 0 ).flatten()\n return pixcoord\n\n def make_cutout ( self, ra, dec, deltaRA, deltaDEC ): \n '''\n Produce a cutout of size deltaRA (in deg) and deltaDEC (in deg)\n ''' \n bands = self.bands\n \n width = deltaRA * (self.pixscale/3600.)**-1 # deg * (arcsec/pix * deg/arcsec)**-1\n height = deltaDEC * (self.pixscale/3600.)**-1 \n \n cutout = MultiBandImage (self.bands, self.zpt, pixscale=self.pixscale)\n for ix, key in enumerate(bands):\n centralcoord = self.sky2pix ( ra, dec, key )\n\n ymin = int(centralcoord[1] - height/2.)\n ymax = int(centralcoord[1] + height/2.)\n xmin = int(centralcoord[0] - width/2.)\n xmax = int(centralcoord[0] + width/2.)\n \n cutout.image[key] = self.image[key][ymin:ymax,xmin:xmax]\n cutout.variance[key] = self.variance[key][ymin:ymax,xmin:xmax]\n cutout.mask[key] = self.mask[key][ymin:ymax,xmin:xmax]\n return cutout \n\n\ndef cutout_from_fits ( name, source_name, cutout_dir): \n #from musulsb.image import MultiBandImage \n cutout = MultiBandImage ( bands='grizy', zpt=27., pixscale=0.168 )\n for band in cutout.bands:\n fname = f'{cutout_dir}/coadds_{source_name}/fmt_{name}_{band}.fits'\n if not os.path.exists(fname):\n print(f'[OSError] {name} does not have imaging in HSC-{band}!')\n continue\n fim = fits.open(fname)\n cutout.image[band] = fim[1].data.byteswap().newbyteorder()\n cutout.mask[band] = fim[2].data.byteswap().newbyteorder()\n cutout.variance[band] = fim[3].data.byteswap().newbyteorder()\n \n pname = f'{cutout_dir}/psfs_{source_name}/psf_{name}_{band}.fits'\n if os.path.exists(pname):\n psf = fits.open(pname)\n cutout.psf[band] = psf[0].data\n else:\n print(f'[OSError] {name} does not have a PSF model for HSC-{band}!')\n cutout.name = name\n cutout.source_name = source_name\n return cutout\n\nclass GalacticExtinction ( FilterBase ):\n def __init__(self, av=None, extinction_path=None, filter_directory='./' ):\n if (av is not None) and (extinction_path is not None):\n raise ValueError (\"Cannot specify both AV and an extinction table!\")\n elif av is not None:\n self.av = av\n else:\n dust_raw = open(extinction_path,'r').readlines()\n dust = pd.read_csv(extinction_path, skiprows=16, \n delim_whitespace=True, names=[ dr[1:] for dr in dust_raw[13].split() ][1:-1])\n dust_indices = pd.read_csv(extinction_path.replace('extinction.tbl','dustmap_indexkey.csv'), index_col=0)\n dust.index = dust_indices.index\n self.galext = dust \n av = self.galext.loc[str(name), 'AV_SandF'] #XXX\n self. av = av\n self.load_filtercurves(prefix_path=filter_directory)\n \n def get_Alambda ( self, Av, filter_name, Rv=3.1 ):\n '''\n Using the package extinction's implementation of the Fitzpatrick+1999 Galactic\n extinction curve, compute A_lambda over a broadband filter.\n '''\n if filter_name not in self.filter_curves.keys():\n raise NameError (f\"{filter_name} is not a filter that has been loaded!\")\n cfilt = self.filter_curves[filter_name]\n\n ftype = cfilt.filter_type\n if ftype == 'photon':\n fn = lambda w,f,t: np.trapz(t*f*w,w)\n elif ftype == 'energy':\n fn = lambda w,f,t: np.trapz(t*f,w)\n\n wv = cfilt.transmission[:,0]\n Alambda_inst = extinction.fitzpatrick99 ( wv, Av, Rv ) \n Alambda_eff = fn (wv, Alambda_inst, cfilt.transmission[:,1] )\n Alambda_eff /= fn(wv, np.ones_like(wv), cfilt.transmission[:,1] )\n #keff = fn(wv, kc, cfilt.transmission[:,1])/fn(wv,np.ones_like(kc),cfilt.transmission[:,1])\n return Alambda_eff #keff * Av / Rv\n \n def deredden ( self, name, filter_name, Rv=3.1, verbose=False ):\n av = self.av \n \n if verbose:\n print(f'[GalExt] extinction over is A_V={av}')\n \n alambda = self.get_Alambda ( av, filter_name, Rv )\n factor = 10**(0.4*alambda)\n return factor\n \n ","repo_name":"ekadofong/ekfutils","sub_path":"ekfphot/ekfphot/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21717929818","text":"import tkinter as tk\nfrom user_interface.setting import Setting\n\n\nclass Window:\n def __init__(self, setting: Setting):\n self.counter = 0\n self.message_list = []\n self.window = tk.Tk()\n\n self.frame = tk.Frame(self.window)\n\n # text box for chat massage\n self.frame.grid(row=0, column=0, columnspan=2, rowspan=3, padx=200, pady=200)\n self.chat_text = tk.Text(master=self.frame)\n self.chat_text.insert(tk.INSERT, \"WELCOME: \" + setting.user_name + \"\\n\")\n self.chat_text.config(state=tk.DISABLED)\n self.chat_text.pack()\n\n # conf tag\n self.chat_text.tag_configure('myself',\n foreground='#476042',\n font=('Tempus Sans ITC', 12, 'bold'))\n self.chat_text.tag_configure('someone',\n foreground='red',\n font=('Tempus Sans ITC', 12, 'bold'))\n # enter box to send\n\n self.frame.grid(row=3, column=1)\n self.text_to_send = tk.Entry(self.frame)\n self.text_to_send.pack()\n\n # button to send\n\n self.frame.grid(row=3, column=0)\n self.button_send = tk.Button(self.frame, command=self.send, text=\"SEND\")\n self.button_send.pack()\n\n self.user_name = setting.user_name\n\n # chosen user \n self.frame.grid(row=3, column=2)\n self.button_chosen = tk.Button(self.frame, command=self.set_choose_user, text=\"chose user\")\n self.button_chosen.pack()\n\n self.chosen_user = \"\"\n\n # enter chosen\n\n self.frame.grid(row=3, column=2)\n self.text_chosen = tk.Entry(self.frame)\n self.text_chosen.pack()\n # say hello\n self.frame.grid(row=3, column=3)\n self.say_hello = tk.Button(self.frame, command=self.say_hello, text=\"say hello\")\n self.say_hello.pack()\n\n # chosen_user\n\n self.chosen_user = \"\"\n\n # client\n self.connector = None\n self.rsa = setting.rsa\n self.is_safe_mode = setting.is_safe_mode\n\n def say_hello(self):\n self.connector.say_hello()\n\n def set_choose_user(self):\n text = self.text_chosen.get()\n if text[0] == '1':\n self.chosen_user = text\n else:\n self.chosen_user = \"1-\" + text\n self.connector.send_ask_for_key(self.chosen_user)\n\n def run(self):\n self.window.mainloop()\n\n def import_connector(self, connector):\n from client.connector import Connector\n self.connector = connector\n\n def send(self):\n message = self.text_to_send.get()\n self.text_to_send.delete(0, \"end\")\n self.message_list.append(message)\n if self.is_safe_mode:\n self.send_safe(message)\n else:\n self.connector.window_to_client(message)\n\n def send_safe(self, message):\n self.connector.send_safe(self.chosen_user, message)\n self.connector.send_safe(self.user_name, message)\n\n def add_message(self, message: str):\n self.message_list.append(message)\n self.chat_text.configure(state=tk.NORMAL)\n if self.its_me(message):\n self.chat_text.insert(tk.END, message + \"\\n\", 'myself')\n else:\n self.chat_text.insert(tk.END, message + \"\\n\", 'someone')\n\n self.chat_text.config(state=tk.DISABLED)\n\n def its_me(self, message: str):\n temp = message.split(\" : \")\n print(temp, \" username \", self.user_name)\n print(\"temp===self\", temp[0] == self.user_name)\n return temp[0] == self.user_name or temp[0] == \">\" + self.user_name\n","repo_name":"piodd/Chat","sub_path":"user_interface/Window.py","file_name":"Window.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"36272422207","text":"#coding:utf8\r\n'''\r\nCreated on 2012-3-19\r\n场景类\r\n@author: Administrator\r\n'''\r\nfrom app.scense.utils.dbopera import dbScene,dbNpc,dbPortals\r\nfrom app.scense.core.PlayersManager import PlayersManager\r\nfrom app.scense.netInterface.pushObjectNetInterface import pushApplyMessage\r\n\r\nfrom firefly.utils.singleton import Singleton\r\nfrom twisted.python import log\r\nimport random\r\n\r\nfrom app.scense.protoFile.scene import pushSceneMessage_pb2,\\\r\n EnterSceneMessage_605_pb2,removePlayerInMap_pb2\r\nfrom app.scense.core.language.Language import Lg\r\nfrom app.scense.applyInterface import configure\r\nfrom app.scense.core.campaign import fortress\r\n \r\nUP = 20\r\n\r\nclass Scene(object):\r\n '''基础场景类'''\r\n \r\n __metaclass__ = Singleton\r\n \r\n def __init__(self):\r\n '''\r\n @param id: int 公共场景的id\r\n @param rooms: int 场景数据房间\r\n '''\r\n self.rooms = []\r\n self._name = Lg().g(272)\r\n \r\n def initPublicSceneData(self,sid):\r\n '''初始化公共场景数据\r\n '''\r\n sceneInfo = dbScene.ALL_PUBLICSCENE_INFO.get(sid,{})\r\n if not sceneInfo:\r\n log.err('public scene %d does not exist'%sid)\r\n return\r\n self._id = sid\r\n self._name = sceneInfo['name']\r\n self._levelrequired = sceneInfo['levelRequired']\r\n self._type = sceneInfo['type']\r\n self._height = sceneInfo['height']#场景的高度\r\n self._width = sceneInfo['width']#场景的宽度\r\n self._init_X = sceneInfo['init_X']#场景进入的初始化x坐标\r\n self._init_Y = sceneInfo['init_Y']#场景进入的初始化x坐标\r\n self._resourceid = sceneInfo['resourceid']#场景的资源ID\r\n self._monsters = {} #怪物列表\r\n# self._playerlist = []#场景角色列表\r\n self._canRec = set([])#场景能够接受场景消息角色列表\r\n self._portals = eval('['+sceneInfo['portals']+']')\r\n self._npclist = eval('['+sceneInfo['npclist']+']')\r\n self._npclistInfo = [dbNpc.ALL_NPCS.get(npcID) for\\\r\n npcID in self._npclist]\r\n self._portalsInfo = [dbPortals.ALL_PORTALS.get(portalId) for\\\r\n portalId in self._portals]\r\n \r\n def getSceneGuildName(self):\r\n '''获取城镇占领国的名称\r\n '''\r\n from app.scense.core.campaign.FortressManager import FortressManager\r\n from app.scense.core.guild.GuildManager import GuildManager\r\n f = FortressManager().getFortressBySceneId(self._id)\r\n if not f.isOccupied:\r\n return ''\r\n if not f.kimori:\r\n return ''\r\n guildId = f.kimori\r\n guild = GuildManager().getGuildById(guildId)\r\n return guild.get('name')\r\n \r\n def getSceneName(self):\r\n '''获取场景的名称'''\r\n return self._name\r\n \r\n def getNPCInfoList(self):\r\n '''获取NPC信息列表\r\n '''\r\n guildname = self.getSceneGuildName()\r\n if not guildname:\r\n return self._npclistInfo\r\n npclist = []\r\n for npcinfo in self._npclistInfo:\r\n npc = dict(npcinfo)\r\n npc['name'] = u'【%s】%s'%(guildname,npcinfo['name'])\r\n npclist.append(npc)\r\n return npclist\r\n \r\n \r\n def addPlayer(self,playerId):\r\n '''添加一个角色到当前场景\r\n @param playerId: int 角色的id\r\n '''\r\n if not self.rooms:\r\n self.rooms.append([])\r\n tag = 0\r\n for room in self.rooms:\r\n if len(room)1 and len(columns)>1:\r\n\r\n X.append(float(columns[0]))\r\n Y.append(float(columns[1]))\r\n\r\n X=np.array(X)\r\n Y=np.array(Y)\r\n return {'X':X , 'Y': Y}\r\n\r\n\r\n def read_Ez(path = _cwd, filename = 'Ez.h5'):\r\n '''\r\n Read the Ez.h5 file containing the Ez field information\r\n '''\r\n\r\n hf = h5py.File(path+filename, 'r')\r\n _log.info('Reading the h5 file: ' + path + filename + ' ...')\r\n _log.debug('Size of the file: ' + str(round((os.path.getsize(path+filename)/10**9),2))+' Gb')\r\n\r\n # get number of datasets\r\n size_hf=0.0\r\n dataset=[]\r\n n_step=[]\r\n for key in hf.keys():\r\n size_hf+=1\r\n dataset.append(key)\r\n n_step.append(int(key.split('_')[1]))\r\n\r\n return hf, dataset\r\n\r\n def read_cst_3d(path = _cwd, path_3d = '3d', filename = 'Ez.h5'):\r\n '''\r\n Read CST 3d exports folder and store the\r\n Ez field information into a matrix Ez(x,y,z) \r\n for every timestep into a `.h5` file\r\n ''' \r\n\r\n # Rename files with E-02, E-03\r\n for file in glob.glob(path_3d +'*E-02.txt'): \r\n file=file.split(path_3d)\r\n title=file[1].split('_')\r\n num=title[1].split('E')\r\n num[0]=float(num[0])/100\r\n\r\n ntitle=title[0]+'_'+str(num[0])+'.txt'\r\n os.rename(path_3d+file[1], path_3d+ntitle)\r\n\r\n for file in glob.glob(path_3d +'*E-03.txt'): \r\n file=file.split(path_3d)\r\n title=file[1].split('_')\r\n num=title[1].split('E')\r\n num[0]=float(num[0])/1000\r\n\r\n ntitle=title[0]+'_'+str(num[0])+'.txt'\r\n os.rename(path_3d+file[1], path_3d+ntitle)\r\n\r\n for file in glob.glob(path_3d +'*_0.txt'): \r\n file=file.split(path_3d)\r\n title=file[1].split('_')\r\n num=title[1].split('.')\r\n num[0]=float(num[0])\r\n\r\n ntitle=title[0]+'_'+str(num[0])+'.txt'\r\n os.rename(path_3d+file[1], path_3d+ntitle)\r\n\r\n fnames = sorted(glob.glob(path_3d+'*.txt'))\r\n\r\n #Get the number of longitudinal and transverse cells used for Ez\r\n i=0\r\n with open(fnames[0]) as f:\r\n lines=f.readlines()\r\n n_rows = len(lines)-3 #n of rows minus the header\r\n x1=lines[3].split()[0]\r\n\r\n while True:\r\n i+=1\r\n x2=lines[i+3].split()[0]\r\n if x1==x2:\r\n break\r\n\r\n n_transverse_cells=i\r\n n_longitudinal_cells=int(n_rows/(n_transverse_cells**2))\r\n\r\n # Create h5 file \r\n if os.path.exists(path+filename):\r\n os.remove(path+filename)\r\n\r\n hf = h5py.File(path+filename, 'w')\r\n\r\n # Initialize variables\r\n Ez=np.zeros((n_transverse_cells, n_transverse_cells, n_longitudinal_cells))\r\n x=np.zeros((n_transverse_cells))\r\n y=np.zeros((n_transverse_cells))\r\n z=np.zeros((n_longitudinal_cells))\r\n t=[]\r\n\r\n nsteps, i, j, k = 0, 0, 0, 0\r\n skip=-4 #number of rows to skip\r\n rows=skip \r\n\r\n # Start scan\r\n for file in fnames:\r\n _log.debug('Scanning file '+ file + '...')\r\n title=file.split(path)\r\n title2=title[1].split('_')\r\n num=title2[1].split('.txt')\r\n t.append(float(num[0])*1e-9)\r\n\r\n with open(file) as f:\r\n for line in f:\r\n rows+=1\r\n columns = line.split()\r\n\r\n if rows>=0 and len(columns)>1:\r\n k=int(rows/n_transverse_cells**2)\r\n j=int(rows/n_transverse_cells-n_transverse_cells*k)\r\n i=int(rows-j*n_transverse_cells-k*n_transverse_cells**2) \r\n \r\n Ez[i,j,k]=float(columns[5])\r\n x[i]=float(columns[0])\r\n y[j]=float(columns[1])\r\n z[k]=float(columns[2])\r\n\r\n if nsteps == 0:\r\n prefix='0'*5\r\n hf.create_dataset('Ez_'+prefix+str(nsteps), data=Ez)\r\n else:\r\n prefix='0'*(5-int(np.log10(nsteps)))\r\n hf.create_dataset('Ez_'+prefix+str(nsteps), data=Ez)\r\n\r\n i, j, k = 0, 0, 0 \r\n rows=skip\r\n nsteps+=1\r\n\r\n #close file\r\n f.close()\r\n\r\n hf.close()\r\n\r\n #set field info\r\n _log.debug('Ez field is stored in a matrix with shape '+str(Ez.shape)+' in '+str(int(nsteps))+' datasets')\r\n _log.info('Finished scanning files - hdf5 file'+filename+'succesfully generated')","repo_name":"ImpedanCEI/wakis","sub_path":"wakis/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"3201164008","text":"import autograd.numpy as np\nimport autograd.numpy.random as npr\n\nfrom autograd import grad\nfrom autograd.misc.optimizers import adam\n\nfrom reg.nn.npy.utils import logistic, relu, linear, tanh\nfrom reg.nn.npy.utils import mse, ce\n\n\nclass NNRegressor:\n\n def __init__(self, sizes, nonlin='tanh',\n output='logistic', loss='ce'):\n\n self.nb_layers = len(sizes) - 2\n self.sizes = sizes\n\n nlist = dict(relu=relu, tanh=tanh, logistic=logistic, linear=linear)\n self.nonlins = [nlist[nonlin]] * self.nb_layers + [nlist[output]]\n\n self.params = [(npr.randn(x, y), npr.randn(y))\n for i, (x, y) in enumerate(zip(self.sizes[:-1], self.sizes[1:]))]\n\n llist = dict(mse=mse, ce=ce)\n self.criterion = llist[loss]\n\n def forward(self, input):\n _output = input\n for i, (w, b) in enumerate(self.params):\n nonlin = self.nonlins[i]\n activation = np.einsum('nk,kh->nh', _output, w) + b\n _output = nonlin(activation)[0]\n return _output\n\n def fit(self, target, input, nb_epochs=500, batch_size=16, lr=1e-3, verbose=True):\n\n nb_batches = int(np.ceil(len(input) / batch_size))\n\n def batch_indices(iter):\n idx = iter % nb_batches\n return slice(idx * batch_size, (idx + 1) * batch_size)\n\n def _objective(params, iter):\n self.params = params\n idx = batch_indices(iter)\n return self.cost(target[idx], input[idx])\n\n def _callback(params, iter, grad):\n if iter % (nb_batches * 10) == 0:\n self.params = params\n if verbose:\n print('Epoch: {}/{}.............'.format(iter // nb_batches, nb_epochs), end=' ')\n print(\"Loss: {:.4f}\".format(self.cost(target, input)))\n\n _gradient = grad(_objective)\n\n self.params = adam(_gradient, self.params, step_size=lr,\n num_iters=nb_epochs * nb_batches, callback=_callback)\n\n def cost(self, target, input):\n _output = self.forward(input)\n return self.criterion(target, _output)[0]\n","repo_name":"pnickl/reg","sub_path":"reg/nn/npy/nn_ag.py","file_name":"nn_ag.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71393173397","text":"import yaml\nimport os\nimport sys\nroot = os.path.abspath('..')\nsys.path.append(root)\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef load_config(file_path):\n with open(file_path, 'r') as f:\n config = yaml.load(f)\n return config\n\ndef load_data(file_path):\n df = pd.read_csv(file_path)\n return df\n\ndef drop_dplicate_columns(df):\n df = df.T.drop_duplicates().T\n return df\n\ndef get_redundant_pairs(df):\n '''Get diagonal and lower triangular pairs of correlation matrix'''\n pairs_to_drop = set()\n cols = df.columns\n for i in range(0, df.shape[1]):\n for j in range(0, i+1):\n pairs_to_drop.add((cols[i], cols[j]))\n return pairs_to_drop\n\ndef get_top_abs_correlations(df, n=5):\n au_corr = df.corr().abs().unstack()\n labels_to_drop = get_redundant_pairs(df)\n au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)\n return au_corr[0:n]\n\ndef create_missing_values_json(df, vars):\n df = df.copy()\n mv_json = {}\n for var in vars:\n mv_json[var] = df[var].isnull().sum()/len(df)\n return mv_json\n\ndef analyze_continuous(df, var):\n df = df.copy()\n df[var].hist(bins = 20)\n\n plt.xlabel(var)\n plt.ylabel('Number of houses')\n plt.tight_layout()\n #plt.savefig(os.path.join(config['PATH']['ANALYSIS_REPORTS_PATH'] + 'continuous_vars', '{}_distribution.png'.format(var)))\n plt.show()\n\ndef find_freq_labels(df, var, rare_pct= 0.90):\n df = df.copy()\n tmp = df[var].value_counts(normalize = True)\n return tmp[tmp > rare_pct].index\n","repo_name":"ChandanVerma/Sample_project","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30822915224","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\n\n\nclass Solution:\n def removeNthFromEnd(self, head, n):\n curr = head\n keep = []\n numToKeep = n + 1\n while curr != None:\n if len(keep) >= numToKeep:\n keep = keep[1:]\n keep.append(curr)\n curr = curr.next\n keep.reverse()\n if n == len(keep):\n return head.next\n elif n == 1:\n keep[n].next = None\n else:\n keep[n].next = keep[n - 2]\n return head\n","repo_name":"peterrauscher/LeetCode","sub_path":"19-remove-nth-node-from-end-of-list.py","file_name":"19-remove-nth-node-from-end-of-list.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7777058455","text":"import numpy as np\nfrom pylab import *\n\n# Definicion de parametros\nN=2000 # Número de pasos\ntau=30 # Tiempo en segundos de la simulación\nh=(tau/float(N-1)) # Paso del tiempo\nM=1 # Masa de los bloques [kg]\nk=1 # Constante de resorte 1\nk1=1.2 # Constante de resorte 2\n\n# Definimos condiciones iniciales\nx1_0 = 0.0 # Posicion inicial de x1\nv1_0 = 0.0 # Velocidad inicial vx1\nx2_0 = 1.0 # Posicion inicial de x2\nv2_0 = 0.0 # Velocidad inicial vx2\n\nalpha1 = (-1/M) * (k1 + k)\nalpha2 = (k/M)\nalpha3 = (k/M)\nalpha4 = (-1/M) * (k1 + k )\n\n# Definimos nuestra ecuación diferencial\ndef f1(t, y):\n f0 = y[1]\n f1 = alpha1*(y[0]+0.1*y[0]**3) + alpha2*(y[2]+0.1*y[2]**3)\n f2 = y[3]\n f3 = alpha3*(y[0]+0.1*y[0]**3) + alpha4*(y[2]+0.1*y[2]**3)\n return [f0, f1, f2, f3]\n\ndef f(t, y):\n f0 = y[1]\n f1 = alpha1*(y[0]) + alpha2*(y[2])\n f2 = y[3]\n f3 = alpha3*(y[0]) + alpha4*(y[2])\n return [f0, f1, f2, f3]\n\nk1 = np.zeros(N)\nk2 = np.zeros(N)\nk3 = np.zeros(N)\nk4 = np.zeros(N)\n\ndef rk4(y,t,h,f) :\n k1 = np.multiply(h, f(t, y))\n k2 = np.multiply(h, f(t + h/2, np.add(y, np.divide(k1, 2))))\n k3 = np.multiply(h, f(t + h/2, np.add(y, np.divide(k2, 2))))\n k4 = np.multiply(h, f(t + h, np.add(y, k3)))\n return np.add(y, np.divide(np.add(np.add(np.add(k1, np.multiply(2, k2)), np.multiply(2, k3)), k4), 6))\n\n\n# Generamos un arreglo de Nx4 para almacenar posiciones y velocidades\ny=np.zeros([N,4])\n# Arreglo para el caso de resorte no lineal\ny1=np.zeros([N,4])\n# Tomamos los valores del estado inicial\ny[0,0]=x1_0 \ny[0,1]=v1_0 \ny[0,2]=x2_0 \ny[0,3]=v2_0 \n\ny1[0,0]=x1_0 \ny1[0,1]=v1_0 \ny1[0,2]=x2_0 \ny1[0,3]=v2_0 \n\n# Generamos tiempos igualmente espaciados\ntiempo=linspace(0,tau,N)\n\nfor i in range(N-1):\n y[i+1] = rk4(y[i], tiempo[i], h, f)\n y1[i+1] = rk4(y1[i], tiempo[i], h, f1)\n\n# Calculamos las frecuencias de los modos normales de vibracion, primero definimos la matriz A\nA = np.array([[alpha1, alpha2], [alpha3, alpha4]])\neigenvalores, eigenvectores = np.linalg.eig(A)\n# Extraemos las frecuencias de los modos normales de vibracion\nomega = np.sqrt(-eigenvalores)\n# Presentamos las frecuencias de los modos normales de vibracion\nprint(f\"Frecuencias de los modos normales de vibracion: {omega}\")\n\n#Graficamos los resultados\n\nx1_datos = np.array([y[j,0] for j in range(N)])\nv1_datos = np.array([y[j,1] for j in range(N)])\nx2_datos = np.array([y[j,2] for j in range(N)])\nv2_datos = np.array([y[j,3] for j in range(N)])\ntiempo = np.array([tiempo[j] for j in range(N)])\n\n# Para el caso no lineal\nnl_x1_datos = np.array([y1[j,0] for j in range(N)])\nnl_v1_datos = np.array([y1[j,1] for j in range(N)])\nnl_x2_datos = np.array([y1[j,2] for j in range(N)])\nnl_v2_datos = np.array([y1[j,3] for j in range(N)])\n\nfigure(figsize=(10, 5))\nplot(tiempo, x1_datos, label='x1(t)')\nplot(tiempo, x2_datos, label='x2(t)')\nplot(tiempo, nl_x1_datos, label='x1(t) [No lineal]')\nplot(tiempo, nl_x2_datos, label='x2(t) [No lineal]')\nxlabel('Tiempo [s]')\nylabel('Desplazamiento [m]')\nlegend()\ntitle('Sistema de resortes acoplados')\nshow()","repo_name":"Jean2330/NumericalPhysics","sub_path":"Tarea_4_2.py","file_name":"Tarea_4_2.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31713340267","text":"import requests\nfrom bs4 import BeautifulSoup\t# pip install beautifulsoup4\nimport bs4\n\ndef getHTMLText(url):\n\tprint(\"getHTMLText\")\n\ttry:\n\t\tr = requests.get(url, timeout = 60)\n\t\tr.raise_for_status()\n\t\tr.encoding = r.apparent_encoding\n\t\treturn r.text\n\texcept Exception as e:\n\t\treturn \"\"\n\ndef fillUnivList(ulist, html):\n\tprint(\"fillUnivList\")\n\tsoup = BeautifulSoup(html, \"html.parser\")\n\tfor tr in soup.find(\"tbody\").children:\n\t\tif isinstance(tr, bs4.element.Tag):\n\t\t\ttds = tr('td')\n\t\t\tulist.append(tds[0].string)\n\ndef printUnivList(ulist, num):\n\tprint(\"printUnivList\")\n\tprint(\"Suc \" + str(num))\n\tfor item in ulist:\n\t\tprint(f\"Element: {item}\")\n\ndef main():\n\tuinfo_list = []\n\tprint(\"Mainxx\")\n\turl = \"https://www.shanghairanking.cn/rankings/bcur/2023\"\n\thtml = getHTMLText(url)\n\tfillUnivList(uinfo_list, html)\n\tprintUnivList(uinfo_list, 20)\n\nmain()\n\n\n\n\n\n","repo_name":"stoull/Notebook","sub_path":"Python/Crawl-Example-Code/CrawlUnivRanking.py","file_name":"CrawlUnivRanking.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"36387161561","text":"EVALUATIONS_DESCRIPTION = {\n \"Company\": {\n \"Fulfillment\": {\n \"Description\": \"This measures how much employees feel their work is meaningful and fulfilling.\"\n },\n \"Autonomy\": {\n \"Description\": \"This gauges the extent to which employees feel they have the freedom and independence to make decisions about their work.\"\n },\n \"GrowthOpportunities\": {\n \"Description\": \"This measures how many opportunities for growth and development the company offers.\"\n },\n \"Workload\": {\n \"Description\": \"This evaluates whether employees perceive their workload as manageable and balanced.\"\n },\n \"Stress\": {\n \"Description\": \"This measures the level of stress employees experience in their work environment.\"\n },\n \"WorkLifeBalance\": {\n \"Description\": \"This gauges how well employees are able to balance their work responsibilities with their personal life.\"\n },\n },\n \"Person\": {\n \"Recognition\": {\n \"Description\": \"This evaluates how often the person is recognized and appreciated for their work.\"\n },\n \"Sympathy\": {\n \"Description\": \"This gauges the extent to which colleagues feel empathetic and understanding towards the person.\"\n },\n \"Trust\": {\n \"Description\": \"This measures how much trust and confidence colleagues place in the person.\"\n },\n \"ProSupport\": {\n \"Description\": \"This measures how much professional support the person offers to their colleagues.\"\n },\n \"GrowthSupport\": {\n \"Description\": \"This evaluates how much support the person provides to their colleagues in terms of growth and development opportunities.\"\n },\n }\n}\n\nEVALUATION_FUNCTIONS_SPEC = [\n {\n \"name\": \"insert_evaluation\",\n \"description\": \"Process and store evaluation criteria for each given target\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"evaluations\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"EvaluationTargetType\": {\"type\": \"integer\",\n \"description\": \"Type of target: 1=Company 2=Person\"},\n \"SubjectUserID\": {\"type\": \"string\", \"description\": \"Person ID\"},\n \"SubjectName\": {\"type\": \"string\", \"description\": \"Person name\"},\n \"Company_Fulfillment\": {\"type\": \"integer\", \"description\": \"Score for company fulfillment\"},\n \"Company_FulfillmentWeight\": {\"type\": \"number\",\n \"description\": \"Weight for company fulfillment score\"},\n \"Company_Autonomy\": {\"type\": \"integer\", \"description\": \"Score for company autonomy\"},\n \"Company_AutonomyWeight\": {\"type\": \"number\",\n \"description\": \"Weight for company autonomy score\"},\n \"Company_GrowthOpportunities\": {\"type\": \"integer\",\n \"description\": \"Score for company growth opportunities\"},\n \"Company_GrowthOpportunitiesWeight\": {\"type\": \"number\",\n \"description\": \"Weight for company growth opportunities score\"},\n \"Company_Workload\": {\"type\": \"integer\", \"description\": \"Score for company workload\"},\n \"Company_WorkloadWeight\": {\"type\": \"number\",\n \"description\": \"Weight for company workload score\"},\n \"Company_Stress\": {\"type\": \"integer\", \"description\": \"Score for company stress\"},\n \"Company_StressWeight\": {\"type\": \"number\",\n \"description\": \"Weight for company stress score\"},\n \"Company_WorkLifeBalance\": {\"type\": \"integer\",\n \"description\": \"Score for company work life balance\"},\n \"Company_WorkLifeBalanceWeight\": {\"type\": \"number\",\n \"description\": \"Weight for company work life balance score\"},\n \"Person_Recognition\": {\"type\": \"integer\", \"description\": \"Score for person recognition\"},\n \"Person_RecognitionWeight\": {\"type\": \"number\",\n \"description\": \"Weight for person recognition score\"},\n \"Person_Sympathy\": {\"type\": \"integer\", \"description\": \"Score for person sympathy\"},\n \"Person_SympathyWeight\": {\"type\": \"number\",\n \"description\": \"Weight for person sympathy score\"},\n \"Person_Trust\": {\"type\": \"integer\", \"description\": \"Score for person trust\"},\n \"Person_TrustWeight\": {\"type\": \"number\", \"description\": \"Weight for person trust score\"},\n \"Person_ProSupport\": {\"type\": \"integer\", \"description\": \"Score for professional support\"},\n \"Person_ProSupportWeight\": {\"type\": \"number\",\n \"description\": \"Weight for professional support score\"},\n \"Person_GrowthSupport\": {\"type\": \"integer\", \"description\": \"Score for growth support\"},\n \"Person_GrowthSupportWeight\": {\"type\": \"number\",\n \"description\": \"Weight for growth support score\"},\n \"SentimentData\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"word\": {\"type\": \"string\", \"description\": \"The word of sentiment\"},\n \"weight\": {\"type\": \"number\",\n \"description\": \"decimal: 0 is negative, 1 is positive\"},\n \"count\": {\"type\": \"integer\",\n \"description\": \"number of appearance\"}\n },\n \"required\": [\n \"word\",\n \"weight\",\n \"count\"\n ]\n }\n },\n },\n \"required\": [\n \"EvaluationTargetType\",\n \"SubjectUserID\",\n \"SubjectUserName\",\n \"Company_Fulfillment\",\n \"Company_FulfillmentWeight\",\n \"Company_Autonomy\",\n \"Company_AutonomyWeight\",\n \"Company_GrowthOpportunities\",\n \"Company_GrowthOpportunitiesWeight\",\n \"Company_Workload\",\n \"Company_WorkloadWeight\",\n \"Company_Stress\",\n \"Company_StressWeight\",\n \"Company_WorkLifeBalance\",\n \"Company_WorkLifeBalanceWeight\",\n \"Person_Recognition\",\n \"Person_RecognitionWeight\",\n \"Person_Sympathy\",\n \"Person_SympathyWeight\",\n \"Person_Trust\",\n \"Person_TrustWeight\",\n \"Person_ProSupport\",\n \"Person_ProSupportWeight\",\n \"Person_GrowthSupport\",\n \"Person_GrowthSupportWeight\"\n ]\n }\n }\n },\n },\n }\n]\n","repo_name":"moneyforward/hackathon-2307T4-wevo","sub_path":"evaluation_specs.py","file_name":"evaluation_specs.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71976167639","text":"# Ejercicio 1: Calculando PI con Monte Carlo\nimport random\nimport matplotlib.pyplot as plt\nimport math\n\nn_puntos = 5000\n\n\ndef dibujar_puntos(puntos):\n \"\"\"\n Dibuja los puntos en un plano.\n Args:\n puntos: lista de tuplas con las coordenadas x e y de los puntos.\n \"\"\"\n x = []\n y = []\n for punto in puntos:\n x.append(punto[0])\n y.append(punto[1])\n plt.scatter(x, y)\n plt.show()\n\n\ndef dibujar_aproximaciones_pi(aproximaciones_pi):\n \"\"\"\n Dibuja las aproximaciones de PI en función del número de puntos generados.\n Args:\n aproximaciones_pi: lista con las aproximaciones de PI.\n \"\"\"\n plt.plot(aproximaciones_pi)\n plt.axhline(y=math.pi, color='C1', linestyle='--')\n plt.show()\n # Crear una barra horizontal con el valor real de pi\n\n\ndef main():\n # Paso 1: Generar puntos aleatorios y dibujarlos\n n_puntos_circulo = 0\n n_puntos_cuadrado = 0\n r_circulo = 1\n puntos_generados = []\n aproximaciones_pi = []\n for i in range(n_puntos):\n x = random.random() * 2 * r_circulo - r_circulo\n y = random.random() * 2 * r_circulo - r_circulo\n puntos_generados.append((x, y))\n if x**2 + y**2 <= r_circulo**2:\n n_puntos_circulo += 1\n n_puntos_cuadrado += 1\n else:\n n_puntos_cuadrado += 1\n if i % 1 == 0:\n aproximaxion_actual = 4 * n_puntos_circulo / n_puntos_cuadrado\n print(f'Aproximación actual de PI después de {i} iteraciones: ', aproximaxion_actual)\n aproximaciones_pi.append(aproximaxion_actual)\n with open('aproximaciones_pi.txt', 'w') as f:\n for aproximacion in aproximaciones_pi:\n f.write(f'{aproximacion}\\n')\n\n # Paso 2: Calcular PI\n pi = 4 * n_puntos_circulo / n_puntos_cuadrado\n print('Aproximacion final de PI = ', pi)\n # dibujar_puntos(puntos_generados)\n dibujar_aproximaciones_pi(aproximaciones_pi)\n\n\nif __name__ == '__main__':\n main()","repo_name":"aitirga/machine_learning_master_course","sub_path":"hydrogeology_master/python_module/class_1/que_habra_aqui/solucion_2.py","file_name":"solucion_2.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"14349376816","text":"import io\nimport os\nfrom io import BytesIO\nimport subprocess\nimport pickle\nimport sqlite3\nimport sys\nimport tempfile\nfrom collections import OrderedDict\nimport xml.etree.ElementTree as etree\nimport networkx as nx\nfrom rdkit import Chem\nfrom rdkit.Chem import Recap\nfrom rdkit.Chem import BRICS\nfrom .auxiliary import calculate_complete_multipartite_graphs, graph_to_ri, graph_info\n\nsqlite3.register_converter(\"PICKLE\", pickle.loads)\n\n\ndef reformat_xml(source, encoding=\"utf8\"):\n with io.open(source, \"r\", encoding=encoding) as xml:\n xml_contents = xml.readlines()\n if \"hmdb\" in xml_contents[1]:\n return source\n\n xml_contents.insert(1, \" \\n\")\n\n with io.open(source, \"w\", encoding=encoding) as xml:\n xml_contents = \"\".join(xml_contents)\n xml.write(xml_contents)\n xml.write(\"\")\n\n return source\n\n\ndef parse_xml(source, encoding=\"utf8\", reformat=True):\n if reformat:\n reformat_xml(source, encoding)\n\n with io.open(source, \"r\", encoding=encoding) as inp:\n record_out = OrderedDict()\n\n xmldec = inp.readline()\n xmldec2 = inp.readline()\n\n xml_record = \"\"\n path = []\n\n for line in inp:\n xml_record += line\n if line == \"\\n\" or line == \"\\n\":\n\n if sys.version_info[0] == 3:\n inp = io.StringIO(xml_record)\n else:\n inp = io.BytesIO(xml_record.encode('utf-8').strip())\n\n for event, elem in etree.iterparse(inp, events=(\"start\", \"end\")):\n if event == 'end':\n path.pop()\n\n if event == 'start':\n path.append(elem.tag)\n if elem.text != None:\n if elem.text.replace(\" \", \"\") != \"\\n\":\n\n path_elem = \".\".join(map(str, path[1:]))\n if path_elem in record_out:\n if type(record_out[path_elem]) != list:\n record_out[path_elem] = [record_out[path_elem]]\n record_out[path_elem].append(elem.text)\n else:\n record_out[path_elem] = elem.text\n\n xml_record = \"\"\n yield record_out\n record_out = OrderedDict()\n\n\nclass ConnectivityDb:\n\n def __init__(self, db):\n self.db = db\n\n\nclass SubstructureDb:\n\n def __init__(self, db, path_pkls, db2=None):\n self.db = db\n self.db2 = db2\n self.path_pkls = path_pkls\n\n self.conn = sqlite3.connect(self.db)\n self.cursor = self.conn.cursor()\n\n if self.db2 is not None:\n self.cursor.execute(\"\"\"ATTACH DATABASE '%s' as 'graphs';\"\"\" % self.db2)\n\n def select_compounds(self, cpds=[]):\n if len(cpds) > 0:\n sql = \" WHERE HMDBID in ('%s')\" % (\", \".join(map(str, cpds)))\n else:\n sql = \"\"\n\n self.cursor.execute(\"\"\"select distinct HMDBID, exact_mass, formula, C, H, N, O, P, S, SMILES,\n SMILES_RDKIT, SMILES_RDKIT_KEK from compounds%s\"\"\" % sql)\n return self.cursor.fetchall()\n\n def filter_hmdbid_substructures(self, min_node_weight):\n self.cursor.execute('DROP TABLE IF EXISTS unique_hmdbid')\n self.cursor.execute('DROP TABLE IF EXISTS filtered_hmdbid_substructures')\n\n self.cursor.execute(\"\"\"create table unique_hmdbid as select distinct HMDBID from compounds\"\"\")\n\n self.cursor.execute(\"\"\"create table filtered_hmdbid_substructures as\n select smiles_rdkit_kek, COUNT(*) from hmdbid_substructures\n group by smiles_rdkit_kek having COUNT(*) >=%s\"\"\" % min_node_weight)\n\n return self.cursor.fetchall()\n\n def generate_substructure_network(self, method=\"default\", min_node_weight=2, remove_isolated=False):\n substructure_graph = nx.Graph()\n self.filter_hmdbid_substructures(min_node_weight)\n\n self.cursor.execute(\"\"\"select * from unique_hmdbid\"\"\")\n unique_hmdb_ids = self.cursor.fetchall()\n\n self.cursor.execute(\"\"\"select * from filtered_hmdbid_substructures\"\"\")\n # add node for each unique substructure, weighted by count\n for unique_substructure in self.cursor.fetchall():\n substructure_graph.add_node(unique_substructure[0], weight=unique_substructure[1])\n\n # generate different flavours of network\n if method == \"default\":\n substructure_graph = self.default_substructure_network(substructure_graph, unique_hmdb_ids)\n elif method == \"extended\":\n substructure_graph = self.extended_substructure_network(substructure_graph, unique_hmdb_ids,\n include_parents=False)\n elif method == \"parent_structure_linkage\":\n substructure_graph = self.extended_substructure_network(substructure_graph, unique_hmdb_ids,\n include_parents=True)\n\n # remove isolated nodes\n if remove_isolated:\n substructure_graph.remove_nodes_from(list(nx.isolates(substructure_graph)))\n\n return substructure_graph\n\n def extended_substructure_network(self, substructure_graph, unique_hmdb_ids, include_parents=False):\n # slower(?) method that allows inclusion of original metabolites\n\n # add node for each parent structure\n for unique_hmdb_id in unique_hmdb_ids:\n substructure_graph.add_node(unique_hmdb_id[0])\n\n # add edge for each linked parent structure and substructure\n self.cursor.execute(\"\"\"select * from hmdbid_substructures where smiles_rdkit_kek in \n (select smiles_rdkit_kek from filtered_hmdbid_substructures)\"\"\")\n for hmdbid_substructures in self.cursor.fetchall():\n substructure_graph.add_edge(hmdbid_substructures[0], hmdbid_substructures[1])\n\n if not include_parents:\n # remove parent structures and replace with linked, weighted substructures\n for unique_hmdb_id in unique_hmdb_ids:\n for adj1 in substructure_graph.adj[unique_hmdb_id[0]]:\n for adj2 in substructure_graph.adj[unique_hmdb_id[0]]:\n if substructure_graph.has_edge(adj1, adj2):\n substructure_graph[adj1][adj2]['weight'] += 1\n else:\n substructure_graph.add_edge(adj1, adj2, weight=1)\n substructure_graph.remove_node(unique_hmdb_id[0])\n\n # remove self-loops and edges below weight threshold\n substructure_graph.remove_edges_from(nx.selfloop_edges(substructure_graph))\n\n return substructure_graph\n\n def default_substructure_network(self, substructure_graph, unique_hmdb_ids):\n # add edges by walking through hmdbid_substructures\n for unique_hmdb_id in unique_hmdb_ids:\n self.cursor.execute(\"\"\"select * from hmdbid_substructures where smiles_rdkit_kek in \n (select smiles_rdkit_kek from filtered_hmdbid_substructures) and hmdbid = '%s'\"\"\"\n % unique_hmdb_id)\n nodes = []\n for substructure in self.cursor.fetchall():\n for node in nodes:\n if substructure_graph.has_edge(substructure[1], node):\n substructure_graph[substructure[1]][node]['weight'] += 1\n else:\n substructure_graph.add_edge(substructure[1], node, weight=1)\n\n nodes.append(substructure[1])\n\n return substructure_graph\n\n def select_mass_values(self, accuracy, heavy_atoms, max_valence, masses):\n mass_values = []\n filter_mass = \"\"\n if type(masses) == list:\n if len(masses) > 0:\n filter_mass = \" AND exact_mass__1 in ({})\".format(\",\".join(map(str, masses)))\n\n self.cursor.execute(\"\"\"SELECT DISTINCT exact_mass__{}\n FROM substructures \n WHERE valence <= {}\n AND heavy_atoms IN ({}){}\n \"\"\".format(accuracy, max_valence, \",\".join(map(str, heavy_atoms)), filter_mass))\n\n records = self.cursor.fetchall()\n for record in records:\n mass_values.append(record[0])\n mass_values.sort()\n return mass_values\n\n def select_ecs(self, exact_mass, heavy_atoms, accuracy, ppm=None):\n if ppm is None:\n mass_statement = \"= \" + str(exact_mass)\n else:\n tolerance = (exact_mass / 1000000) * ppm\n mass_statement = \"< {} AND exact_mass__{} > {}\".format(exact_mass + tolerance,\n accuracy,\n exact_mass - tolerance)\n \n self.cursor.execute(\"\"\"SELECT DISTINCT \n C, \n H, \n N, \n O, \n P, \n S \n FROM substructures \n WHERE heavy_atoms in ({})\n AND exact_mass__{} {}\n \"\"\".format(\",\".join(map(str, heavy_atoms)), accuracy, mass_statement))\n\n return self.cursor.fetchall()\n\n def paths(self, tree, cur=()):\n if tree == {}:\n yield cur\n else:\n for n, s in tree.items():\n for path in self.paths(s, cur + (n,)):\n yield path\n\n def isomorphism_graphs(self, id_pkl):\n with open(os.path.join(self.path_pkls, \"{}.pkl\".format(id_pkl)), 'rb') as pickle_file:\n nGcomplete = pickle.load(pickle_file)\n for p in self.paths(nGcomplete):\n yield p\n\n def k_configs(self):\n self.cursor.execute(\"\"\"SELECT id_pkl, nodes_valences \n FROM subgraphs\"\"\")\n records = self.cursor.fetchall()\n configs = {}\n for record in records:\n configs[str(record[1])] = record[0]\n return configs\n\n def select_sub_structures(self, l_atoms):\n\n subsets = []\n for i in range(len(l_atoms)):\n\n self.cursor.execute(\"\"\"SELECT DISTINCT lib \n FROM substructures\n WHERE C = {} \n AND H = {} \n AND N = {} \n AND O = {}\n AND P = {}\n AND S = {}\n \"\"\".format(l_atoms[i][0], l_atoms[i][1], l_atoms[i][2], l_atoms[i][3], l_atoms[i][4],\n l_atoms[i][5]))\n records = self.cursor.fetchall()\n if len(records) == 0:\n return []\n ss = [pickle.loads(record[0]) for record in records]\n subsets.append(ss)\n\n return subsets\n\n def create_compound_database(self):\n self.cursor.execute('DROP TABLE IF EXISTS compounds')\n self.cursor.execute('DROP TABLE IF EXISTS substructures')\n self.cursor.execute('DROP TABLE IF EXISTS hmdbid_substructures')\n\n self.cursor.execute(\"\"\"CREATE TABLE compounds (\n hmdbid TEXT PRIMARY KEY,\n exact_mass INTEGER,\n formula TEXT,\n C INTEGER,\n H INTEGER,\n N INTEGER,\n O INTEGER,\n P INTEGER,\n S INTEGER,\n smiles TEXT,\n smiles_rdkit TEXT,\n smiles_rdkit_kek TEXT)\"\"\")\n\n self.cursor.execute(\"\"\"CREATE TABLE substructures (\n smiles TEXT PRIMARY KEY, \n heavy_atoms INTEGER,\n length INTEGER,\n exact_mass__1 INTEGER,\n exact_mass__0_1 REAL,\n exact_mass__0_01 REAL,\n exact_mass__0_001 REAL,\n exact_mass__0_0001 REAL,\n exact_mass REAL,\n count INTEGER,\n C INTEGER,\n H INTEGER,\n N INTEGER,\n O INTEGER,\n P INTEGER,\n S INTEGER,\n valence INTEGER,\n valence_atoms TEXT,\n atoms_available INTEGER,\n lib PICKLE)\"\"\")\n\n self.cursor.execute(\"\"\"CREATE TABLE hmdbid_substructures (\n hmdbid TEXT,\n smiles_rdkit_kek,\n PRIMARY KEY (hmdbid, smiles_rdkit_kek))\"\"\")\n\n def create_indexes(self):\n\n self.cursor.execute(\"\"\"DROP INDEX IF EXISTS heavy_atoms__Valence__mass__1__idx\"\"\")\n self.cursor.execute(\"\"\"DROP INDEX IF EXISTS heavy_atoms__Valence__mass__0_1__idx\"\"\")\n self.cursor.execute(\"\"\"DROP INDEX IF EXISTS heavy_atoms__Valence__mass__0_01__idx\"\"\")\n self.cursor.execute(\"\"\"DROP INDEX IF EXISTS heavy_atoms__Valence__mass__0_001__idx\"\"\")\n self.cursor.execute(\"\"\"DROP INDEX IF EXISTS heavy_atoms__Valence__mass__0_0001__idx\"\"\")\n self.cursor.execute(\"\"\"DROP INDEX IF EXISTS atoms__Valence__idx\"\"\")\n\n self.cursor.execute(\"\"\"CREATE INDEX heavy_atoms__Valence__mass__1__idx \n ON substructures (heavy_atoms, valence, valence_atoms, exact_mass__1);\"\"\")\n self.cursor.execute(\"\"\"CREATE INDEX heavy_atoms__Valence__mass__0_1__idx \n ON substructures (heavy_atoms, valence, valence_atoms, exact_mass__0_1);\"\"\")\n self.cursor.execute(\"\"\"CREATE INDEX heavy_atoms__Valence__mass__0_01__idx \n ON substructures (heavy_atoms, valence, valence_atoms, exact_mass__0_01);\"\"\")\n self.cursor.execute(\"\"\"CREATE INDEX heavy_atoms__Valence__mass__0_001__idx \n ON substructures (heavy_atoms, valence, valence_atoms, exact_mass__0_001);\"\"\")\n self.cursor.execute(\"\"\"CREATE INDEX heavy_atoms__Valence__mass__0_0001__idx\n ON substructures (heavy_atoms, valence, valence_atoms, exact_mass__0_0001);\"\"\")\n self.cursor.execute(\"\"\"CREATE INDEX atoms__Valence__idx \n ON substructures (C, H, N, O, P, S, valence, valence_atoms);\"\"\")\n\n def close(self):\n self.conn.close()\n\n\ndef get_substructure(mol, idxs_edges_subgraph, debug=False):\n atom_idxs_subgraph = []\n for bIdx in idxs_edges_subgraph:\n b = mol.GetBondWithIdx(bIdx)\n a1 = b.GetBeginAtomIdx()\n a2 = b.GetEndAtomIdx()\n\n if a1 not in atom_idxs_subgraph:\n atom_idxs_subgraph.append(a1)\n if a2 not in atom_idxs_subgraph:\n atom_idxs_subgraph.append(a2)\n\n atoms_to_dummy = []\n for idx in atom_idxs_subgraph:\n for atom in mol.GetAtomWithIdx(idx).GetNeighbors():\n if atom.GetIdx() not in atom_idxs_subgraph:\n atoms_to_dummy.append(atom.GetIdx())\n\n mol_edit = Chem.EditableMol(mol)\n degree_atoms = {}\n\n # Returns the type of the bond as a double (i.e. 1.0 for SINGLE, 1.5 for AROMATIC, 2.0 for DOUBLE)\n\n for atom in reversed(mol.GetAtoms()):\n\n if atom.GetIdx() in atoms_to_dummy:\n mol_edit.ReplaceAtom(atom.GetIdx(), Chem.Atom(\"*\"))\n\n mol = mol_edit.GetMol()\n mol_edit = Chem.EditableMol(mol)\n\n for atom in reversed(mol.GetAtoms()):\n if atom.GetIdx() not in atom_idxs_subgraph and atom.GetSymbol() != \"*\":\n mol_edit.RemoveAtom(atom.GetIdx())\n\n mol_out = mol_edit.GetMol()\n\n dummies = [atom.GetIdx() for atom in mol_out.GetAtoms() if atom.GetSymbol() == \"*\"]\n\n for atom in mol_out.GetAtoms():\n\n if atom.GetIdx() in dummies:\n\n for atom_n in atom.GetNeighbors():\n\n if atom_n.GetSymbol() == \"*\":\n continue # do not count dummies for valence calculations\n elif atom_n.GetIdx() not in degree_atoms:\n degree_atoms[atom_n.GetIdx()] = 1\n else:\n degree_atoms[atom_n.GetIdx()] += 1\n\n bond_types = {}\n\n for b in mol_out.GetBonds():\n if debug:\n print(b.GetBondTypeAsDouble())\n print(b.GetBondType())\n print(b.GetBeginAtomIdx(), b.GetEndAtomIdx(), mol_out.GetAtomWithIdx(b.GetBeginAtomIdx()).GetSymbol(),\n mol_out.GetAtomWithIdx(b.GetEndAtomIdx()).GetSymbol())\n\n if mol_out.GetAtomWithIdx(b.GetBeginAtomIdx()).GetSymbol() == \"*\":\n if b.GetEndAtomIdx() not in bond_types:\n bond_types[b.GetEndAtomIdx()] = [b.GetBondTypeAsDouble()]\n else:\n bond_types[b.GetEndAtomIdx()].append(b.GetBondTypeAsDouble())\n\n elif mol_out.GetAtomWithIdx(b.GetEndAtomIdx()).GetSymbol() == \"*\":\n if b.GetBeginAtomIdx() not in bond_types:\n bond_types[b.GetBeginAtomIdx()] = [b.GetBondTypeAsDouble()]\n else:\n bond_types[b.GetBeginAtomIdx()].append(b.GetBondTypeAsDouble())\n\n try:\n Chem.rdmolops.Kekulize(mol_out)\n except:\n return None\n\n return {\"smiles\": Chem.MolToSmiles(mol_out, kekuleSmiles=True), # REORDERED ATOM INDEXES,\n \"mol\": mol_out,\n \"bond_types\": bond_types,\n \"degree_atoms\": degree_atoms,\n \"valence\": sum(degree_atoms.values()),\n \"atoms_available\": len(degree_atoms.keys()),\n \"dummies\": dummies}\n\n\ndef get_elements(mol, elements=None):\n if not elements:\n elements = {\"C\": 0, \"H\": 0, \"N\": 0, \"O\": 0, \"P\": 0, \"S\": 0, \"*\": 0}\n mol = Chem.AddHs(mol)\n for atom in mol.GetAtoms():\n elements[atom.GetSymbol()] += 1\n return elements\n\n\ndef calculate_exact_mass(mol, exact_mass_elements=None):\n if not exact_mass_elements:\n exact_mass_elements = {\"C\": 12.0, \"H\": 1.007825, \"N\": 14.003074, \"O\": 15.994915, \"P\": 30.973763, \"S\": 31.972072,\n \"*\": -1.007825}\n exact_mass = 0.0\n mol = Chem.AddHs(mol)\n for atom in mol.GetAtoms():\n atomSymbol = atom.GetSymbol()\n if atomSymbol != \"*\":\n exact_mass += exact_mass_elements[atomSymbol]\n return exact_mass\n\n\ndef filter_records(records, db_type=\"hmdb\"):\n if db_type == \"hmdb\":\n yield from _filter_hmdb_records(records)\n\n\ndef _filter_hmdb_records(records):\n for record in records:\n\n if \"smiles\" in record:\n\n mol = Chem.MolFromSmiles(record['smiles'])\n\n if mol is None:\n continue\n\n if mol.GetNumHeavyAtoms() < 4:\n continue\n\n atom_check = [True for atom in mol.GetAtoms() if atom.GetSymbol() not in [\"C\", \"H\", \"N\", \"O\", \"P\", \"S\"]]\n if len(atom_check) > 0:\n continue\n\n smiles = Chem.rdmolfiles.MolToSmiles(mol, kekuleSmiles=True)\n Chem.rdmolops.Kekulize(mol)\n smiles_rdkit_kek = Chem.rdmolfiles.MolToSmiles(mol, kekuleSmiles=True)\n\n if \"+\" in smiles_rdkit_kek or \"-\" in smiles_rdkit_kek or \"+\" in smiles or \"-\" in smiles:\n # print record['HMDB_ID'], record['smiles'], \"+/-\"\n continue\n\n # try:\n # print(\"%s\\t%s\" % (record['accession'], record['monisotopic_molecular_weight']))\n # except KeyError:\n # print(record['accession'])\n\n els = get_elements(mol)\n exact_mass = calculate_exact_mass(mol)\n\n record_dict = {'HMDB_ID': record['accession'],\n 'formula': record[\"chemical_formula\"],\n 'exact_mass': round(exact_mass, 6),\n 'smiles': record['smiles'],\n 'smiles_rdkit': smiles,\n 'smiles_rdkit_kek': smiles_rdkit_kek,\n 'C': els['C'],\n 'H': els['H'],\n 'N': els['N'],\n 'O': els['O'],\n 'P': els['P'],\n 'S': els['S'],\n 'mol': mol}\n\n yield record_dict\n\n\ndef get_substructure_bond_idx(prb_mol, ref_mol):\n if ref_mol.HasSubstructMatch(prb_mol):\n atom_idx = ref_mol.GetSubstructMatch(prb_mol)\n else:\n return None\n\n bond_idx = ()\n for atom in ref_mol.GetAtoms():\n if atom.GetIdx() in atom_idx:\n for bond in atom.GetBonds():\n # GetBondBetweenAtoms()\n if bond.GetBeginAtomIdx() in atom_idx and bond.GetEndAtomIdx() in atom_idx:\n if bond.GetIdx() not in bond_idx:\n bond_idx = (*bond_idx, bond.GetIdx())\n\n return bond_idx\n\n\ndef subset_sgs_sizes(sgs, n_min, n_max):\n sgs_new = []\n\n for i, edge_idxs in enumerate(sgs):\n edge_idxs_new = []\n\n for j, bonds in enumerate(edge_idxs):\n if n_min <= len(bonds) <= n_max:\n edge_idxs_new.append(bonds)\n\n if len(edge_idxs_new) > 0:\n sgs_new.append(edge_idxs_new)\n\n return sgs_new\n\n\ndef get_sgs(record_dict, n_min, n_max, method=\"exhaustive\"):\n if method == \"exhaustive\":\n return Chem.rdmolops.FindAllSubgraphsOfLengthMToN(record_dict[\"mol\"], n_min, n_max)\n\n elif method == \"RECAP\":\n hierarchy = Recap.RecapDecompose(record_dict[\"mol\"])\n sgs = []\n for substructure in hierarchy.GetAllChildren().values():\n substructure = Chem.DeleteSubstructs(substructure.mol, Chem.MolFromSmarts('[#0]'))\n edge_idxs = get_substructure_bond_idx(substructure, record_dict[\"mol\"])\n if edge_idxs is not None:\n sgs.append(edge_idxs)\n return subset_sgs_sizes([sgs], n_min, n_max)\n\n elif method == \"BRICS\":\n substructures = BRICS.BRICSDecompose(record_dict[\"mol\"])\n sgs = []\n for substructure in substructures:\n substructure = Chem.DeleteSubstructs(Chem.MolFromSmiles(substructure), Chem.MolFromSmarts('[#0]'))\n edge_idxs = get_substructure_bond_idx(substructure, record_dict[\"mol\"])\n if edge_idxs is not None:\n sgs.append(edge_idxs)\n return subset_sgs_sizes([sgs], n_min, n_max)\n\n\ndef update_substructure_database(fn_hmdb, fn_db, n_min, n_max, records=None, method=\"exhaustive\"):\n conn = sqlite3.connect(fn_db)\n cursor = conn.cursor()\n\n if records is None:\n records = parse_xml(fn_hmdb, reformat=False)\n\n for record_dict in filter_records(records):\n\n cursor.execute(\"\"\"INSERT OR IGNORE INTO compounds (\n hmdbid, \n exact_mass, \n formula, \n C, H, N, O, P, S, \n smiles, \n smiles_rdkit, \n smiles_rdkit_kek)\n values (\n :HMDB_ID, \n :exact_mass,\n :formula, \n :C, :H, :N, :O, :P, :S, \n :smiles, \n :smiles_rdkit, \n :smiles_rdkit_kek)\"\"\", record_dict)\n\n # Returns a tuple of 2-tuples with bond IDs\n\n for sgs in get_sgs(record_dict, n_min, n_max, method=method):\n for edge_idxs in sgs:\n lib = get_substructure(record_dict[\"mol\"], edge_idxs)\n if lib is None:\n continue\n\n smiles_rdkit_kek = Chem.rdmolfiles.MolToSmiles(lib[\"mol\"], kekuleSmiles=True)\n\n exact_mass = calculate_exact_mass(lib[\"mol\"])\n els = get_elements(lib[\"mol\"])\n\n pkl_lib = pickle.dumps(lib)\n sub_smi_dict = {'smiles': smiles_rdkit_kek,\n 'exact_mass': exact_mass,\n 'count': 0,\n 'length': sum([els[atom] for atom in els if atom != \"*\"]),\n \"valence\": lib[\"valence\"],\n \"valence_atoms\": str(lib[\"degree_atoms\"]),\n \"atoms_available\": lib[\"atoms_available\"],\n \"lib\": pkl_lib}\n\n sub_smi_dict[\"exact_mass__1\"] = round(sub_smi_dict[\"exact_mass\"], 0)\n sub_smi_dict[\"exact_mass__0_1\"] = round(sub_smi_dict[\"exact_mass\"], 1)\n sub_smi_dict[\"exact_mass__0_01\"] = round(sub_smi_dict[\"exact_mass\"], 2)\n sub_smi_dict[\"exact_mass__0_001\"] = round(sub_smi_dict[\"exact_mass\"], 3)\n sub_smi_dict[\"exact_mass__0_0001\"] = round(sub_smi_dict[\"exact_mass\"], 4)\n\n sub_smi_dict.update(els)\n sub_smi_dict[\"heavy_atoms\"] = sum([els[atom] for atom in els if atom != \"H\" and atom != \"*\"])\n\n cursor.execute(\"\"\"INSERT OR IGNORE INTO substructures (\n smiles, \n heavy_atoms, \n length, \n exact_mass__1, \n exact_mass__0_1, \n exact_mass__0_01, \n exact_mass__0_001, \n exact_mass__0_0001, \n exact_mass, count, \n C, \n H, \n N, \n O, \n P, \n S, \n valence, \n valence_atoms, \n atoms_available, \n lib)\n values (\n :smiles,\n :heavy_atoms,\n :length,\n :exact_mass__1,\n :exact_mass__0_1,\n :exact_mass__0_01,\n :exact_mass__0_001,\n :exact_mass__0_0001,\n :exact_mass,\n :count,\n :C,\n :H,\n :N,\n :O,\n :P,\n :S,\n :valence,\n :valence_atoms,\n :atoms_available,:lib)\n \"\"\", sub_smi_dict)\n\n cursor.execute(\"\"\"INSERT OR IGNORE INTO hmdbid_substructures (\n hmdbid, \n smiles_rdkit_kek) \n VALUES (\"%s\", \"%s\")\n \"\"\" % (record_dict['HMDB_ID'], smiles_rdkit_kek))\n conn.commit()\n conn.close()\n\n\ndef create_isomorphism_database(db_out, pkls_out, boxes, sizes, path_geng=None, path_RI=None):\n conn = sqlite3.connect(db_out)\n cursor = conn.cursor()\n\n cursor.execute('''DROP TABLE IF EXISTS subgraphs''')\n cursor.execute('''CREATE TABLE subgraphs (\n id_pkl INTEGER,\n n_graphs INTEGER,\n graph6 TEXT,\n k INTEGER,\n k_partite TEXT,\n k_valences TEXT,\n nodes_valences TEXT,\n n_nodes INTEGER,\n n_edges INTEGER,\n PRIMARY KEY (graph6, k_partite, nodes_valences)\n );''')\n conn.commit()\n\n id_pkl = 0\n\n for G, p in calculate_complete_multipartite_graphs(sizes, boxes):\n\n print([path_geng, str(G.number_of_nodes()), \"-d1\", \"-D2\", \"-q\"])\n proc = subprocess.Popen([path_geng, str(len(G.nodes)), \"-d1\", \"-D2\", \"-q\"], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n geng_out, err = proc.communicate()\n\n proc.stdout.close()\n proc.stderr.close()\n\n for i, line_geng in enumerate(geng_out.split()):\n\n print(line_geng)\n\n sG = nx.read_graph6(BytesIO(line_geng))\n\n k_gfu = tempfile.NamedTemporaryFile(mode=\"w\", delete=False)\n k_gfu.write(graph_to_ri(G, \"k_graph\"))\n k_gfu.seek(0)\n\n s_gfu = tempfile.NamedTemporaryFile(mode=\"w\", delete=False)\n s_gfu.write(graph_to_ri(sG, \"subgraph\"))\n s_gfu.seek(0)\n\n proc = subprocess.Popen([path_RI, \"mono\", \"geu\", k_gfu.name, s_gfu.name], stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n RI_out, err = proc.communicate()\n\n k_gfu.close()\n s_gfu.close()\n\n mappings = []\n subgraphs = {}\n\n for line in RI_out.decode(\"utf-8\").splitlines():\n if line[0] == \"{\":\n mappings.append(eval(line))\n\n if len(mappings) == 20000:\n gi = graph_info(p, sG, mappings, )\n\n for vn in gi[0]:\n\n if vn not in subgraphs:\n subgraphs[vn] = gi[0][vn]\n # print vn, result[0][vn], result[1][0], result[1][1], len(result[1][1])\n else:\n\n before = len(subgraphs[vn])\n for es in gi[0][vn]:\n if es not in subgraphs[vn]:\n subgraphs[vn].append(es)\n # print vn, es, result[1][0], result[1][1], len(result[1][1])\n after = len(subgraphs[vn])\n print(before, after)\n\n mappings = []\n\n if len(mappings) > 0:\n gi = graph_info(p, sG, mappings, )\n # job = job_server.submit(graphInfo, (p, sG, mappings, ), (valences,), modules=(), globals=globals())\n # jobs.append(job)\n\n for vn in gi[0]:\n\n if vn not in subgraphs:\n subgraphs[vn] = gi[0][vn]\n # print vn, result[0][vn], result[1][0], result[1][1], len(result[1][1])\n else:\n\n before = len(subgraphs[vn])\n for es in gi[0][vn]:\n if es not in subgraphs[vn]:\n subgraphs[vn].append(es)\n # print vn, es, result[1][0], result[1][1], len(result[1][1])\n after = len(subgraphs[vn])\n print(before, after)\n\n if len(subgraphs) > 0:\n\n for vn in subgraphs:\n\n root = {}\n for fr in subgraphs[vn]:\n parent = root\n for e in fr:\n parent = parent.setdefault(e, {})\n\n vt = tuple([sum(v) for v in eval(vn)])\n print(\"INSERT:\", i, line_geng.decode(\"utf-8\"), len(subgraphs[vn]), len(p), str(p), vt, vn,\n sG.number_of_nodes(), sG.number_of_edges())\n\n id_pkl += 1\n cursor.execute('''INSERT INTO subgraphs (id_pkl, \n n_graphs, \n graph6,\n k,\n k_partite,\n k_valences,\n nodes_valences,\n n_nodes, n_edges) \n values (?, ?, ?, ?, ?, ?, ?, ?, ?)''', (\n id_pkl,\n len(subgraphs[vn]),\n line_geng,\n len(p),\n str(p),\n str(vt),\n str(vn),\n sG.number_of_nodes(),\n sG.number_of_edges()))\n pickle.dump(root, open(os.path.join(pkls_out, \"{}.pkl\".format(id_pkl)), \"wb\"))\n conn.commit()\n conn.close()\n","repo_name":"computational-metabolomics/metaboblend","sub_path":"metaboverse/databases.py","file_name":"databases.py","file_ext":"py","file_size_in_byte":33714,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"74504986519","text":"import os\nfrom abc import ABC\nfrom typing import Final\nimport pygame as pg\n\n\nCELL_SIZE: Final = 50\nFPS: Final = 10\n\nGAME_WIDTH: Final = 16\nGAME_HEIGHT: Final = 16\nGAME_RESOLUTION: Final = (GAME_WIDTH * CELL_SIZE, GAME_HEIGHT * CELL_SIZE)\n\n\nclass Color:\n WHITE: Final = pg.Color('white')\n BLACK: Final = pg.Color('black')\n GREEN: Final = pg.Color('green')\n RED: Final = (255, 36, 0)\n GRAY: Final = (50, 50, 50)\n YELLOW: Final = (255, 186, 0)\n\n\nclass PathCtrl(ABC):\n BASE: Final = os.path.dirname(os.path.abspath(__file__))\n ASSET: Final = os.path.join(BASE, 'assets')\n IMAGE: Final = os.path.join(ASSET, 'images')\n\n @classmethod\n def get_img_path(cls, path: str) -> str:\n return os.path.join(cls.IMAGE, path)\n\n @classmethod\n def get_asset_path(cls, path: str) -> str:\n return os.path.join(cls.ASSET, path)\n\n\nclass Keyboard(ABC):\n RIGHT: Final = (pg.K_d, pg.K_RIGHT)\n LEFT: Final = (pg.K_a, pg.K_LEFT)\n UP: Final = (pg.K_w, pg.K_UP)\n DOWN: Final = (pg.K_s, pg.K_DOWN)\n ENTER: Final = (pg.K_SPACE, pg.K_RETURN)\n","repo_name":"BaggerFast/Snake","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"11859211625","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 8 08:59:55 2019\n\n@author: williamdean\nMIdterm problem 3 using central differences to take 1st and 2nd derivative\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.loadtxt( 'midterm_dydx.txt')\n\ntimes, positions = data.T[0], data.T[1]\n\n\ndef central_differences(data, h=1):\n derivative = np.zeros(len(data))\n data = ([0] * h + data + [0] * h)\n for i in range(h, len(data) - h):\n derivative[i - h] = (data[i + h] - data[i - h]) / (2 * h)\n \n return derivative\n\ntime_step = times[1] - times[0]\nh = 1\nd_positions = central_differences(positions, h) / time_step\nd2_positions = central_differences(d_positions[:-h], h) / time_step\n\nplt.plot(times, positions, 'b')\nplt.plot(times[:-h], d_positions[:-h], 'g')\nplt.plot(times[:-4 * h], d2_positions[: -3 * h], 'orange')\nplt.xlabel( 'Time(s)')\nplt.ylabel( 'Position(m)')\nplt.title( 'Objects motion, velocity, and acceleration over time')\nplt.show()\n","repo_name":"huazhige/EART119_Lab","sub_path":"mid-term/deanwilliam/deanwilliam_38830_1312446_midtermp3.py","file_name":"deanwilliam_38830_1312446_midtermp3.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26539343085","text":"import logging\n\nimport settings\n\n\ndef get_logger(name: str='__main__', handler=None, formatter=None):\n if not handler:\n handler = settings.LOG_HANDLER\n\n if not formatter:\n formatter = settings.LOF_FORMATTER\n\n if not handler.formatter:\n handler.setFormatter(formatter)\n\n logger = logging.getLogger(name)\n logger.addHandler(handler)\n logger.setLevel(settings.LOG_LEVEL)\n\n return logger\n","repo_name":"idzhalalov/aiohttp-testing-examples","sub_path":"utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"43808217795","text":"# Created by Vishal Reddy Mandadi on 23-09-2021\n# Q7 of assignment1 SMAI\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef gen_random_nos(n=500):\n random_nos=np.random.uniform(low=0.0, high=1.0, size=(500, 1))\n sum_of_nos=np.sum(random_nos, axis=0)\n return sum_of_nos\n\ndef plot_area_norm_hist(num_arr_np_ar, no_of_bins):\n fig, ax = plt.subplots()\n x, bins, p=ax.hist(num_arr_np_ar, bins=no_of_bins, density=True)# density=True is for normalization\n ax.set(xlabel ='Random numbers', ylabel ='Frequency',\n title ='Normalized Histogram (area under the curve=1)')\n plt.savefig(fname='q7_normalized_hist.png')\n\nif __name__==\"__main__\":\n num_arr = []\n bin_size=1\n no_of_calls=50000\n for i in range(no_of_calls):\n num_arr.append(gen_random_nos())\n #print(\"Random nos sum: {}\".format(gen_random_nos()))\n num_arr_np = np.array(num_arr, dtype=float)\n no_of_bins = int((np.amax(num_arr_np)-np.amin(num_arr_np))/bin_size)\n plot_area_norm_hist(num_arr_np, no_of_bins)\n plt.show()\n #plt.show()\n #print(bins)\n #plt.savefig(fname='normalized_hist.png')\n #plt.savefig('normalized_hist.png')\n # Plotting histograms\n\n \n ","repo_name":"vishal-2000/SMAI-Assignments","sub_path":"Assignment 1/src/q7.py","file_name":"q7.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70477902359","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nX_train = np.linspace(-1, 1, 100)\ny_train = 2 * X_train + np.random.randn(*X_train.shape) * 0.33\n\nmodel = tf.keras.Sequential()\nmodel.add(tf.keras.layers.Dense(1, input_shape=(1,)))\n\nmodel.compile(optimizer='sgd', loss='mean_squared_error')\n\nmodel.fit(X_train, y_train, epochs=50)\n\ny_pred = model.predict(X_train)\n\n\nplt.scatter(X_train, y_train)\nplt.plot(X_train, y_pred, color='red')\nplt.show()\n","repo_name":"neekoh15/tensorflow","sub_path":"LrTF.py","file_name":"LrTF.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8529669339","text":"#!/usr/bin/env python3\n\nimport sys\nfrom random import shuffle\nfrom itertools import permutations\n\n# import numpy as np\n\nfrom utils import *\n\n\ndef main():\n in_file, out_file = sys.argv[1:]\n sys.stdin = open(in_file)\n sys.stdout = open(out_file, 'w', encoding='utf8')\n\n photo_count = int(input())\n photos = [parse_photo(input(), id) for id in range(photo_count)]\n all_tags = set(tag for p in photos for tag in p.tags)\n err('unique tags', len(all_tags))\n\n # shuffle(photos)\n photos.sort(key=lambda photo: (photo.vertical, -len(photo.tags)))\n\n # slides = [i for i in range(photo_count) if photos[i].vertical == False]\n slides = []\n last_vertical = None\n for photo in photos:\n if photo.vertical:\n if last_vertical is None:\n last_vertical = photo\n else:\n slides.append([last_vertical.id, photo.id])\n last_vertical = None\n else:\n slides.append([photo.id])\n\n ITER = 10\n for iter in range(ITER):\n WINDOW = 7 # shuffle in WINDOW-2\n STEP = 1\n for i in range(0, len(slides) - WINDOW, STEP):\n max_score = None\n max_order = None\n for order in permutations(range(i + 1, i + WINDOW - 1)):\n full_order = [i, *order, i + WINDOW - 1]\n score = sum(\n calc_score(photos, slides[a], slides[b])\n for a, b in zip(full_order, full_order[1:])\n )\n # err('full', full_order, score)\n if max_score is None: # first time is in the original order\n max_score = score\n elif score > max_score:\n err(f\"improved score from {max_score} to {score}\")\n max_score = score\n max_order = full_order\n if max_order is not None:\n reordered_slides = [slides[i] for i in max_order]\n # err(reordered_slides)\n slides[i : i + WINDOW] = reordered_slides\n\n print(len(slides))\n for slide in slides:\n print(*slide)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"artemisart/hashcode-2019","sub_path":"mathis_local_opti.py","file_name":"mathis_local_opti.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28984270796","text":"class bowling_game:\n def __init__(self, players):\n self.players = players # while not a requirement it seems like building the capability of many players is easier done now\n self.score = {}\n self.bonus = {}\n for player in players:\n self.score[player] = []\n for player in players:\n self.bonus[player] = []\n\n def display_score(self, player):\n print(\"the score of player {} is {}\".format(player, self.calculate_score(player)))\n\n def calculate_score(self, player):\n bowls = self.score[player]\n total_score = 0\n for i in range(8): # for the first 8 rounds we don't have to worry about bonus two bowls\n if bowls[i][0] == 10: #strike sccore\n frame_score = 10\n if bowls[i+1][0] == 10:\n frame_score += 10 + bowls[i+2][0]\n else:\n frame_score += sum(bowls[i+1])\n elif sum(bowls[i]) == 10: #spare score\n frame_score = 10 + bowls[i+1][0]\n else:\n frame_score = sum(bowls[i])\n total_score += frame_score\n # round nine scoring\n if bowls[8][0] == 10:\n frame_score = 10\n if bowls[9][0] == 10:\n frame_score += (bowls[9][0] + self.bonus[player][0])\n else:\n frame_score += sum(bowls[9])\n elif sum(bowls[8]) == 10: #spare score\n frame_score = 10 + bowls[9][0]\n else:\n frame_score + sum(bowls[8])\n total_score+= frame_score\n # round ten scoring\n if bowls[9][0] == 10:\n total_score += (10 + sum(self.bonus[player]))\n elif sum(bowls[9]) == 10:\n total_score += (10 + self.bonus[player][0])\n else:\n total_score += (sum(bowls[9]))\n return total_score\n\n def play(self):\n for i in range(10):\n self.frame((i+1)) # people don't like counting from 0\n self.bonus_rounds()\n for player in self.players:\n self.display_score(player)\n\n def frame(self, frame_number):\n print(\"frame {}\".format(frame_number))\n frame_bowls = []\n for player in self.players:\n print(\"input player {}'s number of pins taken\".format(player))\n frame_bowls.append(self.roll())\n if frame_bowls[0] < 10:\n print(\"player {} scored {}, input the next lot of pins taken\".format(player, frame_bowls[0]))\n frame_bowls.append(self.roll(limit = (10-frame_bowls[0])))\n self.score[player].append(frame_bowls)\n\n def validator(self, num, limit):\n try:\n num = int(num) # this leave the possibilty of someone inputting a decimal, this could be handled with a replace or regex\n # as we're avoiding imports and I would prefer regex rounding down will do for the moment\n except:\n print(\"Please enter a valid integer\")\n return None\n if num > limit: # can't roll higher than the number of pins standing\n print(\"You can't roll higher than {}, please enter a real bowling score\".format(limit))\n return None\n if num < 0: # sooner or later someone will do it\n print(\"Please explain to the programmer how your roll increased the number of pins present. \\n Please enter a valid number greater than or equal to 0\")\n return None\n return num\n\n def roll(self, limit = 10): # we need to have valiation that the roll is an integer, less than the limit still need to confirm what happens when you give it a decimal\n bowl = input()\n bowl = self.validator(bowl, limit)\n if not bowl:\n bowl = self.roll()\n return bowl\n\n def bonus_rounds(self):\n for player in self.players:\n bonus_scores = []\n if sum(self.score[player][9]) < 10:\n pass\n elif self.score[player][9][0] == 10:\n bonus_scores.append(self.roll())\n bonus_scores.append(self.roll())\n else:\n bonus_scores.append(self.roll())\n self.bonus[player] = bonus_scores\n","repo_name":"alexhautot/coding_test","sub_path":"bowling.py","file_name":"bowling.py","file_ext":"py","file_size_in_byte":4193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17216844114","text":"import math as mt\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nfrom scipy.interpolate import interp1d\n\n\nwde1=np.genfromtxt('printwde.dat')\nz1=wde1[:,0]\nw1=wde1[:,1]\n\nl=len(z1)\n\n\nwde2=np.genfromtxt('printwde_sm.dat')\nz2=wde2[:,0]\nw2=wde2[:,1]\n\nu=np.zeros(l)\nfor i in range (0,l):\n\tu[i]=-1\n\nplt.plot(z1,w1)\n#plt.plot(z2,w2)\n#plt.plot(z1,u)\nplt.show()\n\n","repo_name":"FrancescaGerardi/CosmoMC_binneda_cluster","sub_path":"camb/plot_w.py","file_name":"plot_w.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39052881521","text":"def name_function():\n '''\n DOCSTRING: Information about the name_function\n INPUT: no input...\n OUTPUT: Hello\n '''\n print('Hello')\n\n\nname_function()\n\nhelp(name_function)\n\n# Add default to method parameter\n\n\ndef say_hello(name='NAME'):\n print('Hello '+name)\n\n\nsay_hello('John')\n\nsay_hello()\n\n# Pig Latin example\n\n\ndef pig_latin(word):\n first_letter = word[0]\n # check if vowel\n if first_letter in 'aiueo':\n pig_word = word + 'ay'\n else:\n pig_word = word[1:] + first_letter + 'ay'\n\n return pig_word\n\n\nprint(pig_latin('laptop'))\n","repo_name":"maldyvinandar/udemy-python-exercises","sub_path":"FunctionsExercise.py","file_name":"FunctionsExercise.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15073522125","text":"# reads in a file and returns list of all the words in the file\n# removes punctuations from the strings\n# lowercase all the strings\ndef getWords(filename):\n with open(filename) as f:\n lines = f.read().split()\n # removing punctuations from the list\n removechar = str.maketrans('', '', '.,()!\"?;')\n comp = [s.translate(removechar) for s in lines]\n for i in range(len(comp)):\n comp[i] = comp[i].lower()\n return comp\n\n# accepts list of words and counts occurences, returning a dictionary\n# each iteration of words to KEY\n# each count of words to VALUE\ndef countWords(wordList):\n word_dictionary = dict((x, wordList.count(x)) for x in set(wordList))\n return word_dictionary\n\n\n# displays the counts after accepting a dictionary containing those counts from countWords\n# take key from dictionary input into list\n# sort the list alphabetically\n# print the key and it's value(word count)\ndef display(wordDict):\n makeList = []\n for x in wordDict:\n makeList.append(x)\n makeList.sort()\n for i in makeList:\n print(i + \":\", wordDict[i])\n \n# main function with filename input\ndef main(filename):\n listit = getWords(filename)\n dictit = countWords(listit)\n display(dictit)\n\nmain('testfile.txt')","repo_name":"jdrich1289/mycode","sub_path":"wordSearch.py","file_name":"wordSearch.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12687282230","text":"def maxCiclo(num):\r\n\trestos = []\r\n\tresto = 1%num\r\n\trestos.append(resto)\r\n\tfor j in range(1,num):\r\n\t\tresto = (resto*10) % i\r\n\t\tif resto == 0: \r\n\t\t\treturn 0\r\n\t\tif resto in restos:\r\n\t\t\treturn j\r\n\t\trestos.append(resto)\r\n\r\nif __name__ == '__main__':\r\n\t_max = 0\r\n\t_maxi = -1\r\n\tfor i in range(2,1000):\r\n\t\tciclo = maxCiclo(i)\r\n\t\tif ciclo > _max:\r\n\t\t\t_max = ciclo\r\n\t\t\t_maxi = i\r\n\tprint(\"1/{i} >> ciclo de comprimento {n}\".format(i=_maxi,n=_max))\t\t\r\n\r\n","repo_name":"PPinto22/ProjectEuler","sub_path":"p026.py","file_name":"p026.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19992547590","text":"from django.shortcuts import render, redirect\nfrom .models import Task\nfrom .forms import TaskForm\n\n\ndef home(request):\n # Call all the subjects in database\n subjects = Task.objects.all()\n context = {\"subjects\": subjects}\n return render(request, 'listSubjects/home.html', context)\n\n\ndef add(request):\n if request.method == \"POST\":\n form = TaskForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect(\"home\")\n else:\n form = TaskForm()\n\n context = {\"form\": form}\n return render(request, 'listSubjects/add.html', context)\n\n\ndef delete(request, task_id):\n task = Task.objects.get(id=task_id)\n task.delete()\n return redirect(\"home\")\n\n\ndef update(request, task_id):\n task = Task.objects.get(id=task_id)\n if request.method == \"POST\":\n form = TaskForm(request.POST, instance=task)\n if form.is_valid():\n form.save()\n return redirect(\"home\")\n\n else:\n form = TaskForm(instance=task)\n\n context = {\"form\": form}\n return render(request, 'listSubjects/update.html', context)\n","repo_name":"JhonathanMusa/django-todo-list","sub_path":"listSubjects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38217305659","text":"# coding=utf-8\n__author__ = 'Alexey'\n\nimport redis\n\n\nclass OperationsUpdate(object):\n @staticmethod\n def change_user_name(database, user_id, name):\n \"\"\"\n Функція виконує заміну імені користувача, заданого id, на нове.\n :param database: Підключення до бази даних.\n :param user_id: Номер користувача, заданий цілим числом.\n :param name: Нове ім'я користувача.\n :return: Функція нічого не повертає.\n \"\"\"\n database.set(\"user:%d:name\" % user_id, name)\n\n @staticmethod\n def change_user_emails(database, user_id, emails):\n \"\"\"\n Функція виконує заміну списку адрес електронних пошт користувача, заданого id, на новий.\n :param database: Підключення до бази даних.\n :param user_id: Номер користувача, заданий цілим числом.\n :param emails: Список рядків-адрес електронних пошт користувача.\n :return: Функція нічого не повертає.\n \"\"\"\n #database.set(\"user:%d:emails\" % user_id, emails)\n\n database.delete(\"user:%d:emails\" % user_id)\n #for email in database.smembers(\"user:%d:emails\" % user_id):\n #atabase.srem(\"user:%d:emails\" % user_id, email)\n\n for email in emails:\n database.sadd(\"user:%d:emails\" % user_id, email)","repo_name":"Myshj/Architecture3","sub_path":"UserDatabaseWork/OperationsUpdate.py","file_name":"OperationsUpdate.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"69918101717","text":"import cv2\nimport numpy as np\nfrom scipy import ndimage\n\n\"\"\"\nThe code here might help to improve\ndetection in the parquimetros dataset!\nLook at g_hpf!!\n\"\"\"\n\nkernel_3x3 = np.array([[-1, -1, -1],\n [-1, 8, -1],\n [-1, -1, -1]])\nkernel_5x5 = np.array([[-1, -1, -1, -1, -1],\n [-1, 1, 2, 1, -1],\n [-1, 2, 4, 2, -1],\n [-1, 1, 2, 1, -1],\n [-1, -1, -1, -1, -1]])\n\nimg_path = 'Parquimetros/2018-12-22 17.27.43.jpg'\nimg = cv2.imread(img_path, 0)\nimg = cv2.resize(img, (512, 512))\n\nk3 = ndimage.convolve(img, kernel_3x3)\nk5 = ndimage.convolve(img, kernel_5x5)\n\nblurred = cv2.GaussianBlur(img, (17, 17), 0)\ng_hpf = img - blurred\n\ncv2.imshow('Original image', img)\ncv2.imshow('3x3', k3)\ncv2.imshow('5x5', k5)\ncv2.imshow('blurred', blurred)\ncv2.imshow('g_hpf', g_hpf)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"hernandezurbina/CVAdventures","sub_path":"hpf_filter.py","file_name":"hpf_filter.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32769681840","text":"from matplotlib import pyplot as plt\n\n\n# 绘制横版条形图\nfigure = plt.figure(figsize=(14, 8), dpi=80)\n\na = [\"战狼2\", \"速度与激情8\", \"西游伏魔篇\", \"变形金刚5:\\n最后的骑士大哥哥\",\n \"生化危机6\", \"美丽心灵\", \"哪咤脑海\", \"流浪地球\", \"开心人\"]\n\nb = [56.01, 26.94, 94.17, 53.16, 12.96, 70.14, 44.67, 39.63, 59.58]\n\n# x和y的位置跟bar()一样,只是后面的width参数变成了height\n# height参数用来控制柱子的粗细\nplt.barh(a, b, height=0.3, color=\"orange\")\n\n# 注意下面的xticks原本是yticks,因为xy轴颠倒了所以要改成xticks \nplt.xticks(range(0, 110, 10))\n\nplt.title(\"2017年前5大电影票房排行\", fontsize=16)\nplt.grid(alpha=0.3)\n\nplt.show()\n","repo_name":"lengke/dataplay","sub_path":"mat107.py","file_name":"mat107.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10892632667","text":"import torch\nimport torch.nn as nn\n\nfrom ..utils import get_transformer, pairs\n\nclass FlatTransModel(nn.Module):\n def __init__(self, system, class_num=1):\n super().__init__()\n self.transformer = get_transformer(system)\n self.classifier = nn.Linear(768, class_num)\n\n def forward(self, x, mask):\n h1 = self.transformer(input_ids=x, attention_mask=mask).last_hidden_state[:,0]\n y = self.classifier(h1)\n return y\n\nclass FlatSegModel(nn.Module):\n def __init__(self, system, class_num=1):\n super().__init__()\n self.transformer = get_transformer(system)\n self.classifier = nn.Linear(768, 1)\n self.sigmoid = nn.Sigmoid()\n \n def forward(self, x, mask):\n h1 = self.transformer(input_ids=x, attention_mask=mask).last_hidden_state\n y = self.classifier(h1).squeeze(-1)\n y = self.sigmoid(y)\n return y\n \n def get_phrases(self, ids, mask, thresh=0.5):\n #convert all turns to phrase boundary predictions\n y = self.forward(ids, mask)\n \n phrases = []\n for turn_ids, probs in zip(ids, y):\n #for each turn, select all positions above threshold\n decisions = [1] + list((probs > thresh).nonzero(as_tuple=True)[0])\n segments = pairs(decisions)\n \n #Create phrases\n for start, end in segments:\n segment = turn_ids[start:end]\n phrases.append([101] + segment.tolist() + [102])\n\n return phrases\n \n \n \n \n ","repo_name":"adianliusie/dialogue_act_modelling","sub_path":"src/models/basic_models.py","file_name":"basic_models.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4883530530","text":"# Preço de uma viagem\nfrom time import sleep\n\ncores = {\n 'limpo': '\\033[m',\n 'verde': '\\033[32m',\n 'amarelo': '\\033[33m'\n}\n\nlinha_verde = f'{cores[\"verde\"]}-=-' * 11 + f'{cores[\"limpo\"]}'\n\n\ndef analise_preco(km):\n if km <= 200:\n preco = km * 0.5\n else:\n preco = km * 0.45\n return preco\n\n\ndef main():\n\n print(\n f'{linha_verde}\\n{cores[\"amarelo\"]}Preço da viagem...{cores[\"limpo\"]}\\n{linha_verde}')\n\n km = str(input('Digite a distância de sua viagem: ')).strip()\n km = float(km.split()[0])\n print(linha_verde)\n\n sleep(1)\n\n print(f'{cores[\"amarelo\"]}ANALISANDO...')\n print(linha_verde)\n\n sleep(1)\n\n preco = analise_preco(km)\n\n print(\n f'Sua viagem vai custar: {cores[\"amarelo\"]}R${preco:.2f}{cores[\"limpo\"]}\\n{linha_verde}')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"BEp0/Estudos_de_Python","sub_path":"estruturas_condicionais/ex026_200km.py","file_name":"ex026_200km.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"24437027384","text":"class Solution:\n def maxArea(self, height: List[int]) -> int:\n ans = 0\n \n # we will use two pointers, left and right, to search through height from both ends\n left = 0\n right = len(height)-1\n \n while left < right:\n # if the left height is bigger than the right height\n if height[left] > height[right]:\n # update the answer if the amount of water contained by these two heights is bigger\n ans = max(ans, (right-left)*height[right])\n # since the right height was smaller, let's change that pointer\n # we don't want to change the left height since it was larger\n right -= 1\n else:\n # update the answer if the amount of water contained by these two heights is bigger\n ans = max(ans, (right-left)*height[left])\n # like before, we want to increase the left pointer now and hope that it will\n # lead to a bigger height, thus leading to more water stored in the container\n left += 1\n \n return ans","repo_name":"Bloomh/LeetCode-Submissions","sub_path":"0011-container-with-most-water/0011-container-with-most-water.py","file_name":"0011-container-with-most-water.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29252678901","text":"import sys\n\ndef meets_criteria_part1(value):\n numeral_array = list(str(value))\n if len(numeral_array) != 6:\n return False\n \n repeat_exists = False\n prev_val = 0\n for string_val in numeral_array:\n int_val = int(string_val)\n if int_val < prev_val: return False\n if int_val == prev_val: repeat_exists = True\n prev_val = int_val\n\n return repeat_exists\n\ndef meets_criteria_part2(value):\n numeral_array = list(str(value))\n if len(numeral_array) != 6:\n return False\n\n repeat_clusters = []\n current_repeat_cluster = []\n\n prev_val = 0\n for string_val in numeral_array:\n int_val = int(string_val)\n if int_val < prev_val: return False\n elif int_val == prev_val:\n if (len(current_repeat_cluster) > 0):\n current_repeat_cluster.append(int_val)\n else:\n current_repeat_cluster.append(int_val)\n current_repeat_cluster.append(int_val)\n elif (len(current_repeat_cluster) > 0):\n repeat_clusters.append(current_repeat_cluster.copy())\n current_repeat_cluster = []\n prev_val = int_val\n\n if (len(current_repeat_cluster) > 0):\n repeat_clusters.append(current_repeat_cluster.copy())\n current_repeat_cluster = []\n\n repeat_exists = False\n for cluster in repeat_clusters:\n if len(cluster) == 2: repeat_exists = True\n\n return repeat_exists\n \n\ndef valid_values_in_range_part1(min_val, max_val):\n valid_values = [x for x in range(min_val, max_val) if meets_criteria_part1(x)]\n return len(valid_values)\n\n\ndef valid_values_in_range_part2(min_val, max_val):\n valid_values = [x for x in range(min_val, max_val) if meets_criteria_part2(x)]\n return len(valid_values)\n\nif __name__ == '__main__':\n print(\"Valid values in range in part 1: {0}\".format(valid_values_in_range_part1(int(sys.argv[1]), int(sys.argv[2]))))\n print(\"Valid values in range in part 2: {0}\".format(valid_values_in_range_part2(int(sys.argv[1]), int(sys.argv[2]))))\n","repo_name":"AliceLovesCode/AdventOfCode2019","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29483080098","text":"# https://www.acmicpc.net/problem/10282\n\nfrom math import inf\nimport sys \nimport heapq\ninput = sys.stdin.readline\n\ndef dikstra(start_node, nodes) :\n dist = [inf] * (len(nodes)+1) # dist[i] : i까지 오는데 걸리는 거리\n dist[start_node] = 0 # 자기 자신까지의 거리는 0\n Q = []\n heapq.heappush(Q, (dist[start_node], start_node))\n while Q : \n cur_dist, cur_node = heapq.heappop(Q)\n if dist[cur_node] < cur_dist : # 현재 노드까지 오는데 걸린 거리(dist[cur_node])보다 방금 지난 edge의 거리가 크다면\n continue # 고려 대상에서 제외한다\n for (w, n) in nodes[cur_node] : \n if dist[n] > cur_dist + w : \n dist[n] = cur_dist + w\n heapq.heappush(Q, (cur_dist+w,n)) # (노드를 방문했을 때의 거리, 노드)\n return dist\n\nT = int(input()) \nfor _ in range(T) : \n N, D, C = map(int, input().split()) \n nodes = [[] for _ in range(N+1)] # nodes[i] : (weight, node)\n for _ in range(D) : \n a, b, s = map(int, input().split())\n nodes[b].append((s,a))\n dist = dikstra(C, nodes)\n answer = [i for i in dist if i != inf]\n print(len(answer), max(answer))","repo_name":"GyuhoonK/algorithm","sub_path":"baekjoon/10282_해킹.py","file_name":"10282_해킹.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71980099799","text":"import datetime\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import train_test_split\n\nfrom hmmd import HMM\n\n\ndef get_data(fname, split_sequences):\n word2id = {}\n pos2id = {}\n\n X = []\n Y = []\n\n curr_id = 0\n curr_pos_id = 0\n with open(fname, 'r') as fin:\n x = []\n y = []\n for line in fin:\n line = line.rstrip()\n if not line:\n if x and y:\n X.append(x[:])\n Y.append(y[:])\n x.clear()\n y.clear()\n else:\n cols = line.split(' ')\n if len(cols) == 3:\n token, pos, bio = cols\n if token not in word2id:\n word2id[token] = curr_id\n curr_id += 1\n if pos not in pos2id:\n pos2id[pos] = curr_pos_id\n curr_pos_id += 1\n x.append(word2id[token])\n y.append(pos2id[pos])\n # # Debug\n # x.append(token)\n # y.append(pos)\n\n print(len(X), len(Y), curr_id, curr_pos_id)\n\n print(X[0], Y[0])\n\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.15)\n\n print(len(X_train), len(Y_train), len(X_test), len(Y_test))\n return X_train, Y_train, X_test, Y_test, word2id, {v:k for k, v in pos2id.items()}\n\n\ndef accuracy(T, Y):\n n_correct = 0\n n_total = 0\n for t, y in zip(T, Y):\n n_correct += np.sum(t == y)\n n_total += len(y)\n return float(n_correct) / n_total\n\n\ndef total_f1_score(T, Y):\n T = np.concatenate(T)\n Y = np.concatenate(Y)\n return f1_score(T, Y, average='macro')\n\n\ndef main(fname, smoothing=10e-2):\n Xtrain, Ytrain, Xtest, Ytest, word2id, id2pos = get_data(fname, split_sequences=True)\n V = len(word2id) + 1\n\n M = max(max(y) for y in Ytrain) + 1\n A = np.ones((M, M)) * smoothing\n pi = np.zeros(M)\n for y in Ytrain:\n pi[y[0]] += 1\n for i in range(len(y) - 1):\n A[y[i], y[i+1]] += 1\n A /= A.sum(axis=1, keepdims=True)\n pi /= pi.sum()\n\n B = np.ones((M, V)) * smoothing\n for x, y in zip(Xtrain, Ytrain):\n for xi, yi in zip(x, y):\n B[yi, xi] += 1 # The state is the target here, needs to be 1st dim!\n B /= B.sum(axis=1, keepdims=True)\n\n hmm = HMM(M)\n hmm.pi = pi\n hmm.A = A\n hmm.B = B\n\n Ptrain = []\n for x in Xtrain:\n p = hmm.get_state_sequence(x)\n Ptrain.append(p)\n \n Ptest = []\n for x in Xtest:\n p = hmm.get_state_sequence(x)\n Ptest.append(p)\n\n print('Train accuracy: {}'.format(accuracy(Ytrain, Ptrain)))\n print('Train f1: {}'.format(total_f1_score(Ytrain, Ptrain)))\n print('Test accuracy: {}'.format(accuracy(Ytest, Ptest)))\n print('Test f1: {}'.format(total_f1_score(Ytest, Ptest)))\n\n\nif __name__ == '__main__':\n main(sys.argv[1])\n","repo_name":"fortiema/udemy_lazyprog","sub_path":"hmm/pos_tagger.py","file_name":"pos_tagger.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18630697429","text":"import pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\n\ni_filepath=os.path.dirname(__file__)\npd.set_option('display.max_columns',None) #顯示所有列\npd.set_option('display.max_columns',None) #顯示所有列\npd.set_option('max_colwidth',100) #顯示值(最大長度100)\n\ndf=pd.read_csv(i_filepath+'\\\\Iris\\\\Iris.csv')\ndf=df.drop(df.columns[0],axis=1) #刪除Id\ndf=df.drop_duplicates() #刪除重複的\n# print(df.info())\ndf[df.columns[4]]=df[df.columns[4]].map({'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2 })\n# print(df.info())\n\n##設定特徵值\ndf_x=df[[df.columns[0],df.columns[1],df.columns[2],df.columns[3]]]\n\n##建立kmean模型\n# k=1 #分幾群\n# km=KMeans(n_clusters=k)\n\n# ##訓練模型\n# km.fit(df_x)\n\n##檢測準確性\n# print('分群準確性:',km.inertia_) #km.inertia_所有資料點和所屬中心群中心的距離總和\n\n# ##檢測哪一個k值最好\n# s = []\n# for k in range(1,15):\n# km = KMeans(n_clusters=k)\n# km.fit(df_x)\n# s.append(km.inertia_)\n# print(s)\n\n# ## 看視覺化圖表決定參數K值\n# df_kmeans = pd.DataFrame()\n# df_kmeans['inertia_'] = s\n# df_kmeans.index = list(range(1,15)) \n# df_kmeans.plot(grid=True)\n# plt.show()\n# #可選下降幅度由快速轉為平緩的k值\n\n##選k=3\nk=3 \nkm=KMeans(n_clusters=k)\nkm.fit(df_x)\n\n##以測試集進行預測\nprint('分群的預測結果:')\npred = km.fit_predict(df_x) \nprint(pred) \n\n##進行分群預測\ndf1 = df_x.copy()\ndf1['pred'] = pred #最右邊加入一行資料\nc = {0:'r', 1:'g', 2:'b'}\ndf1['colors'] = df1['pred'].map(c)\nprint(df1.columns)\ndf1.plot(kind='scatter', x='SepalLengthCm',y='SepalWidthCm',c=df1['colors'])\nplt.show()\n","repo_name":"chung-chia0201/machine-learning","sub_path":"Iris/ML_lris_kmean.py","file_name":"ML_lris_kmean.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"72827263639","text":"import os\nimport re\nfrom string import Template\n\nfrom .hdf_dot_config_file import HdfDotConfigFile\nimport hdf_utils\n\n\nclass HdfModuleKconfigFile(object):\n def __init__(self, root, module, k_path):\n self.root = root\n self.module = module\n self.k_path = k_path\n self.module_models = {\n 'self': {},\n 'children': []\n }\n self.lines = []\n self.dot_config = None\n self.config_re = re.compile(r'\\s*config\\s+([a-zA-Z0-9_\\-]+)')\n self.depends_on_re = re.compile(r'depends\\s+on\\s+([a-zA-Z0-9_\\-]+)')\n self.choice_re = re.compile(r'^\\s*choice\\s*$')\n self.endchoice_re = re.compile(r'^\\s*endchoice\\s*$')\n self.config_splitter = 'DRIVERS_HDF_'\n self.top_res = [\n (self.config_re, self._parse_config),\n (self.choice_re, self._parse_choice),\n (self.endchoice_re, None)\n ]\n\n def _add_model(self, name_, config_item_, depends_on_item_, enabled_):\n model = {'name': name_,\n 'config_item': config_item_,\n 'depends_on_item': depends_on_item_,\n 'enabled': enabled_}\n if name_ == self.module:\n self.module_models['self'] = model\n else:\n self.module_models['children'].append(model)\n\n def _is_any_top_res_match(self, line):\n for re_pair in self.top_res:\n if re_pair[0].search(line):\n return True\n return False\n\n def _block_top_match(self, current_index, parent_item):\n line = self.lines[current_index]\n for re_pair in self.top_res:\n match_obj = re_pair[0].search(line)\n if match_obj:\n func = re_pair[1]\n if func:\n return func(match_obj, current_index, parent_item)\n return 0\n\n def _parse_config(self, match_obj, start, parent_item):\n config_item = match_obj.group(1)\n parts = config_item.split(self.config_splitter)\n valid_parts = [part for part in parts if part]\n if not valid_parts:\n return\n config_name = valid_parts[-1].lower()\n depends_on_item = ''\n end = start + 1\n while end < len(self.lines):\n line = self.lines[end]\n match_obj = self.depends_on_re.search(line)\n if match_obj:\n depends_on_item = match_obj.group(1)\n break\n if self._is_any_top_res_match(line):\n break\n end += 1\n if not depends_on_item:\n depends_on_item = parent_item\n block_lines = end - start\n else:\n block_lines = end - start + 1\n enabled = self.dot_config.is_enabled(config_item, depends_on_item)\n self._add_model(config_name, config_item, depends_on_item, enabled)\n return block_lines\n\n def _parse_choice(self, _match_obj, start, _parent_item):\n end = start + 1\n common_depends_on_item = ''\n depends_on_obj = None\n while end < len(self.lines):\n line = self.lines[end]\n match_obj = self.depends_on_re.search(line)\n if match_obj:\n if not depends_on_obj:\n depends_on_obj = match_obj\n common_depends_on_item = match_obj.group(1)\n end += 1\n continue\n if self.endchoice_re.search(line):\n end += 1\n return end - start + 1\n consumed = self._block_top_match(end, common_depends_on_item)\n if consumed:\n end += consumed\n else:\n end += 1\n\n def get_models(self):\n if not os.path.exists(self.k_path):\n return\n self.lines = hdf_utils.read_file_lines(self.k_path)\n dot_config_path = hdf_utils.get_liteos_a_dot_config_path(self.root)\n self.dot_config = HdfDotConfigFile(dot_config_path)\n index = 0\n while index < len(self.lines):\n consume = self._block_top_match(index, '')\n if consume:\n index += consume\n else:\n index += 1\n return self.module_models\n\n def _get_driver_kconfig_item(self, driver):\n templates_dir = hdf_utils.get_templates_lite_dir()\n template = os.path.join(templates_dir, 'hdf_driver_kconfig.template')\n template_str = hdf_utils.read_file(template)\n mod_converter = hdf_utils.WordsConverter(self.module)\n drv_converter = hdf_utils.WordsConverter(driver)\n data_model = {\n 'driver_upper_case': drv_converter.upper_case(),\n 'driver_lower_case': drv_converter.lower_case(),\n 'module_upper_case': mod_converter.upper_case()\n }\n config_item = 'DRIVERS_HDF_%s' % drv_converter.upper_case()\n depends_on_item = 'DRIVERS_HDF_%s' % mod_converter.upper_case()\n config_option = {'name': drv_converter.lower_case(),\n 'config_item': config_item,\n 'depends_on_item': depends_on_item,\n 'enabled': False}\n config = Template(template_str).safe_substitute(data_model)\n return config_option, config\n\n def _get_begin_end_flag(self, driver):\n id_ = hdf_utils.get_id(self.module, driver)\n begin_flag = '\\n# /', view=contactoCreateView.as_view(), name=\"contacto\"),\n path('expediente//', view=expedienteDetailView.as_view(), name=\"expediente\"),\n path(\"dashboard-medico/\", view=medicoGeneralView.as_view(), name=\"dashboard-medico\"),\n path(\"crear-solicitud//\", view=solicitudCreateView.as_view(), name=\"crear-solicitud\"),\n path(\"detalle-solicitud//\", view=solicitudCitaDetalleCreateView.as_view(), name=\"detalle-solicitud\"),\n path(\"eliminar-detalle-solicitud//\", view=solicitudDeleteView.as_view(), name=\"eliminar-detalle-solicitud\"),\n path(\"lista-solicitudes/\", view=solicitudesListaView.as_view(), name=\"lista-solicitudes\"),\n path(\"editar-solicitud//\", view=solicitudCitaDetalleUpdateView.as_view(), name=\"editar-solicitud\"),\n path(\"crear-backup/\", view=BackupsDB.as_view(), name=\"crear-backup\"),\n path(\"configuraciones/\", view=configuracionesView.as_view(), name=\"configuraciones\"),\n path(\"descargar//\", view=configuracionesView.descargar_bak, name=\"descargar\"),\n path(\"eliminar-backup//\", view=BackupsDB.eliminar_backup, name=\"eliminar-backup\"),\n path(\"ver-detalle-solicitud//\", view=ver_detalle_solicitud.as_view(), name=\"ver-detalle-solicitud\"),\n]\n","repo_name":"zombozo/senes-proteges","sub_path":"asilo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"36187054982","text":"\nimport atexit\nimport sys\n\n\ndef linebuffered_stdout():\n \"\"\" Always line buffer stdout so pipes and redirects are CLI friendly. \"\"\"\n if sys.stdout.line_buffering:\n return sys.stdout\n orig = sys.stdout\n new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors,\n line_buffering=True)\n new.mode = orig.mode\n return new\n\nsys.stdout = linebuffered_stdout()\n\n\ndef ignore_broken_pipe():\n \"\"\" If a shellish program has redirected stdio it is subject to erroneous\n \"ignored\" exceptions during the interpretor shutdown. This essentially\n beats the interpretor to the punch by closing them early and ignoring any\n broken pipe exceptions. \"\"\"\n for f in sys.stdin, sys.stdout, sys.stderr:\n try:\n f.close()\n except BrokenPipeError:\n pass\n\natexit.register(ignore_broken_pipe)\n\n\nfrom .command import * # noqa\nfrom .autocommand import * # noqa\n","repo_name":"mayfield/shellish","sub_path":"shellish/command/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"7881231560","text":"import quex.engine.state_machine.index as sm_index\nfrom quex.engine.generator.skipper.common import line_counter_in_loop, \\\n end_delimiter_is_subset_of_indentation_counter_newline, \\\n get_character_sequence, \\\n get_on_skip_range_open, \\\n line_column_counter_in_loop\nfrom quex.engine.generator.languages.address import __nice, get_label\nimport quex.engine.generator.languages.variable_db as variable_db\nfrom quex.blackboard import setup as Setup\nfrom quex.engine.misc.string_handling import blue_print\nimport quex.blackboard as blackboard\nfrom quex.blackboard import E_StateIndices\nfrom copy import copy\n\ndef do(Data):\n ClosingSequence = Data[\"closer_sequence\"]\n ModeName = Data[\"mode_name\"]\n\n assert type(ModeName) in [str, unicode]\n assert Data.has_key(\"indentation_counter_terminal_id\")\n \n indentation_counter_terminal_id = Data[\"indentation_counter_terminal_id\"]\n\n Mode = None\n if ModeName != \"\":\n Mode = blackboard.mode_db[ModeName]\n\n code_str, db = get_skipper(ClosingSequence, Mode, indentation_counter_terminal_id) \n\n return code_str, db\n\ntemplate_str = \"\"\"\n $$DELIMITER_COMMENT$$\n text_end = QUEX_NAME(Buffer_text_end)(&me->buffer);\n$$LC_COUNT_COLUMN_N_POINTER_DEFINITION$$\n\n$$ENTRY$$\n QUEX_BUFFER_ASSERT_CONSISTENCY(&me->buffer);\n __quex_assert(QUEX_NAME(Buffer_content_size)(&me->buffer) >= Skipper$$SKIPPER_INDEX$$L );\n\n /* NOTE: If _input_p == end of buffer, then it will drop out immediately out of the\n * loop below and drop into the buffer reload procedure. */\n\n /* Loop eating characters: Break-out as soon as the First Character of the Delimiter\n * (FCD) is reached. Thus, the FCD plays also the role of the Buffer Limit Code. There\n * are two reasons for break-out:\n * (1) we reached a limit (end-of-file or buffer-limit)\n * (2) there was really the FCD in the character stream\n * This must be distinguished after the loop was exited. But, during the 'swallowing' we\n * are very fast, because we do not have to check for two different characters. */\n *text_end = Skipper$$SKIPPER_INDEX$$[0]; /* Overwrite BufferLimitCode (BLC). */\n_$$SKIPPER_INDEX$$_LOOP:\n $$INPUT_GET$$ \n $$IF_INPUT_EQUAL_DELIMITER_0$$\n goto _$$SKIPPER_INDEX$$_LOOP_EXIT;\n $$ENDIF$$\n$$LC_COUNT_IN_LOOP$$\n $$INPUT_P_INCREMENT$$ /* Now, BLC cannot occur. See above. */\n goto _$$SKIPPER_INDEX$$_LOOP;\n_$$SKIPPER_INDEX$$_LOOP_EXIT:\n\n *text_end = QUEX_SETTING_BUFFER_LIMIT_CODE; /* Reset BLC. */\n\n /* Case (1) and (2) from above can be distinguished easily: \n *\n * (1) Distance to text end == 0: \n * End-of-File or Buffer-Limit. \n * => goto to drop-out handling\n *\n * (2) Else: \n * First character of delimit reached. \n * => For the verification of the tail of the delimiter it is \n * essential that it is loaded completely into the buffer. \n * For this, it must be required:\n *\n * Distance to text end >= Delimiter length \n *\n * _input_p end\n * | | end - _input_p >= 3\n * [ ][R][E][M][#] \n * \n * The case of reload should be seldom and is costy anyway. \n * Thus let's say, that in this case we simply enter the drop \n * out and start the search for the delimiter all over again.\n *\n * (2.1) Distance to text end < Delimiter length\n * => goto to drop-out handling\n * (2.2) Start detection of tail of delimiter\n *\n */\n if( QUEX_NAME(Buffer_distance_input_to_text_end)(&me->buffer) < (ptrdiff_t)Skipper$$SKIPPER_INDEX$$L ) {\n /* (2.1) Reload required. */\n goto $$GOTO_RELOAD$$;\n }\n $$LC_ON_FIRST_DELIMITER$$\n /* (2.2) Test the remaining delimiter, but note, that the check must restart at '_input_p + 1'\n * if any later check fails. */\n $$INPUT_P_INCREMENT$$\n /* Example: Delimiter = '*', '/'; if we get ...[*][*][/]... then the the first \"*\" causes \n * a drop out out of the 'swallowing loop' and the second \"*\" will mismatch \n * the required \"/\". But, then the second \"*\" must be presented to the\n * swallowing loop and the letter after it completes the 'match'.\n * (The whole discussion, of course, is superflous if the range delimiter has length 1.) */\n$$DELIMITER_REMAINDER_TEST$$ \n {\n /* NOTE: The initial state does not increment the input_p. When it detects that\n * it is located on a buffer border, it automatically triggers a reload. No \n * need here to reload the buffer. */\n$$LC_COUNT_END_PROCEDURE$$\n /* No need for re-entry preparation. Acceptance flags and modes are untouched after skipping. */\n $$GOTO_AFTER_END_OF_SKIPPING$$ /* End of range reached. */\n }\n\n$$RELOAD$$:\n QUEX_BUFFER_ASSERT_CONSISTENCY_LIGHT(&me->buffer);\n /* -- When loading new content it is checked that the beginning of the lexeme\n * is not 'shifted' out of the buffer. In the case of skipping, we do not care about\n * the lexeme at all, so do not restrict the load procedure and set the lexeme start\n * to the actual input position. */\n $$MARK_LEXEME_START$$\n\n$$LC_COUNT_BEFORE_RELOAD$$\n /* -- According to case (2.1) is is possible that the _input_p does not point to the end\n * of the buffer, thus we record the current position in the lexeme start pointer and\n * recover it after the loading. */\n me->buffer._input_p = text_end;\n if( QUEX_NAME(Buffer_is_end_of_file)(&me->buffer) == false ) {\n QUEX_NAME(buffer_reload_forward)(&me->buffer, (QUEX_TYPE_CHARACTER_POSITION*)position, PositionRegisterN);\n /* Recover '_input_p' from lexeme start \n * (inverse of what we just did before the loading) */\n $$INPUT_P_TO_LEXEME_START$$\n /* After reload, we need to increment _input_p. That's how the game is supposed to be played. \n * But, we recovered from lexeme start pointer, and this one does not need to be incremented. */\n text_end = QUEX_NAME(Buffer_text_end)(&me->buffer);\n$$LC_COUNT_AFTER_RELOAD$$\n QUEX_BUFFER_ASSERT_CONSISTENCY(&me->buffer);\n $$GOTO_ENTRY$$\n }\n /* Here, either the loading failed or it is not enough space to carry a closing delimiter */\n $$INPUT_P_TO_LEXEME_START$$\n $$ON_SKIP_RANGE_OPEN$$\n\"\"\"\n\ndef get_skipper(EndSequence, Mode=None, IndentationCounterTerminalID=None, OnSkipRangeOpenStr=\"\"):\n assert type(EndSequence) == list\n assert len(EndSequence) >= 1\n assert map(type, EndSequence) == [int] * len(EndSequence)\n\n local_variable_db = {}\n\n global template_str\n\n LanguageDB = Setup.language_db\n\n # Name the $$SKIPPER$$\n skipper_index = sm_index.get()\n\n # Determine the $$DELIMITER$$\n delimiter_str, delimiter_comment_str = get_character_sequence(EndSequence)\n delimiter_length = len(EndSequence)\n\n tmp = []\n LanguageDB.COMMENT(tmp, \" Delimiter: %s\" % delimiter_comment_str)\n delimiter_comment_str = \"\".join(tmp)\n # Determine the check for the tail of the delimiter\n delimiter_remainder_test_str = \"\"\n if len(EndSequence) != 1: \n txt = \"\"\n i = 0\n for letter in EndSequence[1:]:\n i += 1\n txt += \" %s\\n\" % LanguageDB.ASSIGN(\"input\", LanguageDB.INPUT_P_DEREFERENCE(i-1))\n txt += \" %s\" % LanguageDB.IF_INPUT(\"!=\", \"Skipper$$SKIPPER_INDEX$$[%i]\" % i)\n txt += \" %s\" % LanguageDB.GOTO(skipper_index)\n txt += \" %s\" % LanguageDB.END_IF()\n delimiter_remainder_test_str = txt\n\n if not end_delimiter_is_subset_of_indentation_counter_newline(Mode, EndSequence):\n goto_after_end_of_skipping_str = LanguageDB.GOTO(E_StateIndices.ANALYZER_REENTRY)\n else:\n # If there is indentation counting involved, then the counter's terminal id must\n # be determined at this place.\n assert IndentationCounterTerminalID is not None\n # If the ending delimiter is a subset of what the 'newline' pattern triggers \n # in indentation counting => move on to the indentation counter.\n goto_after_end_of_skipping_str = LanguageDB.GOTO_TERMINAL(IndentationCounterTerminalID)\n\n if OnSkipRangeOpenStr != \"\": on_skip_range_open_str = OnSkipRangeOpenStr\n else: on_skip_range_open_str = get_on_skip_range_open(Mode, EndSequence)\n\n # The main part\n code_str = blue_print(template_str,\n [\n [\"$$DELIMITER_COMMENT$$\", delimiter_comment_str],\n [\"$$INPUT_P_INCREMENT$$\", LanguageDB.INPUT_P_INCREMENT()],\n [\"$$INPUT_P_DECREMENT$$\", LanguageDB.INPUT_P_DECREMENT()],\n [\"$$INPUT_GET$$\", LanguageDB.ACCESS_INPUT()],\n [\"$$IF_INPUT_EQUAL_DELIMITER_0$$\", LanguageDB.IF_INPUT(\"==\", \"Skipper$$SKIPPER_INDEX$$[0]\")],\n [\"$$ENDIF$$\", LanguageDB.END_IF()],\n [\"$$ENTRY$$\", LanguageDB.LABEL(skipper_index)],\n [\"$$RELOAD$$\", get_label(\"$reload\", skipper_index)],\n [\"$$GOTO_ENTRY$$\", LanguageDB.GOTO(skipper_index)],\n [\"$$INPUT_P_TO_LEXEME_START$$\", LanguageDB.INPUT_P_TO_LEXEME_START()],\n # When things were skipped, no change to acceptance flags or modes has\n # happend. One can jump immediately to the start without re-entry preparation.\n [\"$$GOTO_AFTER_END_OF_SKIPPING$$\", goto_after_end_of_skipping_str], \n [\"$$MARK_LEXEME_START$$\", LanguageDB.LEXEME_START_SET()],\n [\"$$DELIMITER_REMAINDER_TEST$$\", delimiter_remainder_test_str],\n [\"$$ON_SKIP_RANGE_OPEN$$\", on_skip_range_open_str],\n ])\n\n # Line and column number counting\n code_str, reference_p_f = __lc_counting_replacements(code_str, EndSequence)\n\n # The finishing touch\n code_str = blue_print(code_str,\n [[\"$$SKIPPER_INDEX$$\", __nice(skipper_index)],\n [\"$$GOTO_RELOAD$$\", get_label(\"$reload\", skipper_index)]])\n\n if reference_p_f:\n variable_db.enter(local_variable_db, \"reference_p\", Condition=\"QUEX_OPTION_COLUMN_NUMBER_COUNTING\")\n\n variable_db.enter(local_variable_db, \"Skipper%i\", \"{ %s }\" % delimiter_str, delimiter_length, Index=skipper_index)\n variable_db.enter(local_variable_db, \"Skipper%iL\", \"%i\" % delimiter_length, Index=skipper_index)\n variable_db.enter(local_variable_db, \"text_end\")\n return code_str, local_variable_db\n\ndef __lc_counting_replacements(code_str, EndSequence):\n \"\"\"Line and Column Number Counting(Range Skipper):\n \n -- in loop if there appears a newline, then do:\n increment line_n\n set position from where to count column_n\n -- at end of skipping do one of the following:\n if end delimiter contains newline:\n column_n = number of letters since last new line in end delimiter\n increment line_n by number of newlines in end delimiter.\n (NOTE: in this case the setting of the position from where to count\n the column_n can be omitted.)\n else:\n column_n = current_position - position from where to count column number.\n\n NOTE: On reload we do count the column numbers and reset the column_p.\n \"\"\"\n LanguageDB = Setup.language_db\n\n\n def get_character_n_after_last_newline(Sequence):\n tmp = copy(Sequence)\n tmp.reverse()\n try: return tmp.index(ord('\\n'))\n except: return -1\n\n char_n_after_last_newline = get_character_n_after_last_newline(EndSequence)\n\n reference_p_def = \"\"\n\n in_loop = \"\"\n end_procedure = \"\"\n before_reload = \"\"\n after_reload = \"\"\n on_first_delimiter = \"\"\n\n reference_p_required_f = False\n\n # Line/Column Counting:\n newline_number_in_delimiter = EndSequence.count(ord('\\n'))\n\n if EndSequence == map(ord, \"\\n\") or EndSequence == map(ord, \"\\r\\n\"):\n # (1) If the end-delimiter is a newline \n # => there cannot appear a newline inside the comment\n # => IN LOOP: no line number increment\n # no reference pointer required for column counting\n end_procedure += \" __QUEX_IF_COUNT_COLUMNS_SET((size_t)1);\\n\" \n end_procedure += \" __QUEX_IF_COUNT_LINES_ADD((size_t)1);\\n\"\n\n else:\n # (2) If end-delimiter is NOT newline\n # => there can appear a newline inside the comment\n if newline_number_in_delimiter == 0:\n # -- no newlines in delimiter => line and column number \n # must be counted.\n in_loop = line_column_counter_in_loop()\n end_procedure = \" __QUEX_IF_COUNT_COLUMNS_ADD((size_t)(QUEX_NAME(Buffer_tell_memory_adr)(&me->buffer)\\n\" + \\\n \" - reference_p));\\n\" \n reference_p_required_f = True\n else:\n # -- newline inside delimiter => line number must be counted\n # column number is fixed.\n end_procedure = \" __QUEX_IF_COUNT_COLUMNS_SET((size_t)%i);\\n\" \\\n % (char_n_after_last_newline + 1)\n\n if EndSequence[0] == ord('\\n') \\\n or len(EndSequence) > 1 and EndSequence[0:2] == [ord('\\r'), ord('\\n')]: \n # If the first character in the sequence is newline, then the line counting\n # may is prevented by the loop exit. Now, we need to count.\n on_first_delimiter = \"/* First delimiter char was a newline */\\n\" + \\\n \" __QUEX_IF_COUNT_LINES_ADD((size_t)1);\\n\" \n end_procedure += \" __QUEX_IF_COUNT_LINES_ADD((size_t)%i);\\n\" % (newline_number_in_delimiter - 1)\n else:\n in_loop = line_counter_in_loop()\n end_procedure += \" __QUEX_IF_COUNT_LINES_ADD((size_t)%i);\\n\" % newline_number_in_delimiter\n\n \n if reference_p_required_f:\n reference_p_def = \" __QUEX_IF_COUNT_COLUMNS(reference_p = QUEX_NAME(Buffer_tell_memory_adr)(&me->buffer));\\n\"\n before_reload = \" __QUEX_IF_COUNT_COLUMNS_ADD((size_t)(QUEX_NAME(Buffer_tell_memory_adr)(&me->buffer)\\n\" + \\\n \" - reference_p));\\n\" \n after_reload = \" __QUEX_IF_COUNT_COLUMNS(reference_p = QUEX_NAME(Buffer_tell_memory_adr)(&me->buffer));\\n\"\n\n if len(EndSequence) > 1:\n end_procedure = \"%s\\n%s\" % (LanguageDB.INPUT_P_ADD(len(EndSequence)-1), end_procedure)\n\n return blue_print(code_str,\n [[\"$$LC_COUNT_COLUMN_N_POINTER_DEFINITION$$\", reference_p_def],\n [\"$$LC_COUNT_IN_LOOP$$\", in_loop],\n [\"$$LC_COUNT_END_PROCEDURE$$\", end_procedure],\n [\"$$LC_COUNT_BEFORE_RELOAD$$\", before_reload],\n [\"$$LC_COUNT_AFTER_RELOAD$$\", after_reload],\n [\"$$LC_ON_FIRST_DELIMITER$$\", on_first_delimiter],\n ]), \\\n reference_p_required_f\n\n\n","repo_name":"liancheng/rose","sub_path":"external/quex-0.63.2/quex/engine/generator/skipper/range.py","file_name":"range.py","file_ext":"py","file_size_in_byte":16427,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"85"} +{"seq_id":"30353679856","text":"# -*- coding: utf-8 -*-\n\nimport protokoll as prot\nfrom pathlib import Path\nimport os\nimport pandas as pd\nimport hilfe_statistik as hs\n\nclass Vertrieb():\n\n def __init__(self, f_dict):\n \n file_protokoll=f_dict.get('protokoll_file_vertrieb')\n self.oprot = prot.Protokoll(file_protokoll)\n \n self.file_vertrieb = f_dict.get('file_vertrieb') #hier wird das Neugeschäft reingeschriben\n text ='Vertrieb/__Init__: File für die Angaben zum Neugeschäft festgelegt: ' + self.file_vertrieb\n self.oprot.SchreibeInProtokoll(text)\n\n self.optionen_file_grundeinstellungen = f_dict.get('optionen_file_grundeinstellungwindow') #hier stehen die Grunddaten bzw. Marktdaten\n \n self.provisionMarktBu = 0\n self.provisionMarktRente = 0\n self.erwarteteAnzahlRente = 0\n self.erwarteteAnzahlBu = 0\n self.streuungImNG = ''\n \n self.dtype_dic= { 'nr':int, 'jahr':int, 'tkz':int, 'name':str, 'wert':str}\n \n self.LegeFileVertrieb()\n \n self.eigaben_dict={}\n \n self.LeseMarkDaten()\n\n def LeseCsvOptinen(self, file, key):\n wert = \"\"\n df=pd.read_csv(file, sep=\";\")\n df1 = df[df.key == key]\n \n if df1.empty:\n wert=\"\"\n text='Vertrieb/LeseCsvOptinen: Kein Eintrag gefunden. Es wurde null verwendet: key='+str(print(key))\n print(text)\n else:\n index=df1.index[0]\n wert=df1.at[index, 'wert']\n \n return wert \n\n def LeseMarkDaten(self):\n file = self.optionen_file_grundeinstellungen\n \n #Wert für erwartete Anzahl Bu:\n key = 'anzahlMarktBu'\n wert = self.LeseCsvOptinen(file, key)\n self.erwarteteAnzahlBu = wert\n \n #Wert für Provison Bu:\n key = 'provisionMarktBu'\n wert = self.LeseCsvOptinen(file, key)\n self.provisionMarktBu = wert\n \n #Wert für Provison Renten:\n key = 'provisionMarktRente'\n wert = self.LeseCsvOptinen(file, key)\n self.provisionMarktRente = wert\n\n #Wert für erwartete Anzahl Rente:\n key = 'anzahlMarktRente'\n wert = self.LeseCsvOptinen(file, key)\n self.erwarteteAnzahlRente = wert\n\n #Wert für Streuung im Neugeschäft:\n key = 'streuungImNG'\n wert = self.LeseCsvOptinen(file, key)\n self.streuungImNG = wert\n\n\n def LegeTabelleVertriebAn(self):\n datei=self.file_vertrieb\n ocsv=pd.DataFrame()\n ocsv['nr']=None\n ocsv['jahr']=None\n ocsv['tkz']=None\n ocsv['name']=None\n ocsv[\"wert\"]=None\n \n ocsv[['nr', 'jahr', 'tkz', 'name', 'wert']] = ocsv[['nr', 'jahr', 'tkz', 'name', 'wert']].astype(str)\n ocsv.to_csv(datei, ';', index=False)\n \n text='Vertrieb/LegeTabelleVertriebAn: Tabelle fuer Vertrieb/Neugeschäft wurde angelegt: '+str(datei)\n self.oprot.SchreibeInProtokoll(text)\n\n \n def LegeFileVertrieb(self):\n datei= Path(self.file_vertrieb)\n if datei.is_file():\n text=\"Vertrieb/LegeFileVertrieb \" +str(datei)+ \" existiert bereits. Daher muss die Datein zuerst entfernt werden.\"\n print(text)\n self.oprot.SchreibeInProtokoll(text)\n os.remove(datei)\n else:\n print(\"Vertrieb/LegeFileVertrieb: \" +str(datei)+ \" existiert nicht!!!\") \n \n self.LegeTabelleVertriebAn()\n \n def LeseNummer(self):\n datei=self.file_vertrieb\n df=pd.read_csv(datei, sep=\";\", dtype=self.dtype_dic)\n df1 = df.nr\n\n if df1.__len__() == 0 :\n nr=0\n text=\"Vertrieb/LeseNummer: Kein Eintrag in der Datei gefunden: \" +str(datei)\n self.oprot.SchreibeInProtokoll(text)\n\n else:\n try:\n nr=df1.max()\n except:\n nr=0\n text=\"Vertrieb/LeseNummer: die maximale Nummer konnte nicht ermittelt werden: \" +str(df1)\n self.oprot.SchreibeInProtokoll(text)\n \n return nr\n \n def LeseAusCSV(self, key_dict):\n datei=self.file_vertrieb\n df=pd.read_csv(datei, sep=\";\", dtype=self.dtype_dic)\n \n nr=key_dict.get('nr')\n jahr=key_dict.get('jahr')\n tkz=key_dict.get('tkz')\n name=key_dict.get('name')\n \n df1 = df[(df.nr == str(nr)) & (df.jahr == str(jahr)) & (df.tkz == str(tkz)) & (df.name==str(name))]\n \n if df1.__len__() == 0:\n wert=''\n text='Vertrieb/LeseAusCSV: kein Eintrag in der Tabelle gefunden. Es wurde null verwendet. Key: '+str(key_dict)\n self.oprot.SchreibeInProtokoll(text)\n else:\n index=df1.index[0]\n wert=df1['wert'][index]\n\n return wert\n \n def ZeileLoeschenInCSV(self, eintrag_dict):\n datei=self.file_vertrieb\n df=pd.read_csv(datei, sep=\";\", dtype=self.dtype_dic)\n \n nr=eintrag_dict.get('nr')\n jahr=eintrag_dict.get('jahr')\n tkz=eintrag_dict.get('tkz')\n name=eintrag_dict.get('name') \n \n if self.LeseAusCSV(eintrag_dict) != '':\n df = pd.read_csv(datei, sep=';')\n df1 = df[(df.nr != str(nr)) & (df.jahr != str(jahr)) & (df.tkz != str(tkz)) & (df.name != str(name))]\n df1.to_csv(datei, ';', index=False)\n \n text='Vertrieb/ZeileLoeschenInCSV: Eintrag in der Tabelle geloescht: nr='+str(nr)+'jahr='+str(jahr)+' tkz='+str(tkz) +' name='+str(name)\n self.oprot.SchreibeInProtokoll(text)\n\n \n def SchreibeInTabelleVertrieb(self, eintrag_dict):\n datei=self.file_vertrieb\n \n nr=eintrag_dict.get('nr')\n jahr=eintrag_dict.get('jahr')\n tkz=eintrag_dict.get('tkz')\n name=eintrag_dict.get('name')\n wert=eintrag_dict.get('wert')\n \n if self.LeseAusCSV(eintrag_dict) != '':\n self.ZeileLoeschenInSACSV(eintrag_dict)\n \n text=str(nr)+';'+str(jahr)+';'+str(tkz)+';'+str(name)+';'+str(wert)+'\\n'\n f=open(datei, \"a\")\n f.write(text) \n f.close() \n \n def ErmittleAnzahl(self, anzahl_dict):\n #hier wird die Anzahl der Verträge im Neugeschäft ermittelt:\n \n erwarteteAnzahl = float(anzahl_dict.get('erwaerteteAnzahl'))\n beitragZumMarkt = float(anzahl_dict.get('beitragZumMarkt'))\n provisionZumMarkt = float(anzahl_dict.get('provisionZumMarkt'))\n \n stat_dict = {}\n stat_dict['risiko'] = anzahl_dict.get('streuungImNG')\n ohs = hs.Hilfe_Statistik(stat_dict)\n zufallszahl = ohs.NeueZufallszahl()\n nv = ohs.Phi(zufallszahl)\n \n wert = erwarteteAnzahl / beitragZumMarkt * provisionZumMarkt * nv\n \n if wert < 0: #es werten nur positive Werte zugelassen:\n wert = 0\n \n return wert\n \n def SchreibeNeugeschaeft(self, vertrieb_dict):\n #hier wird die Struktur und die Hoehe des Neugeschäfts festgeleht:\n satz_dict={}\n jahr=int(vertrieb_dict.get('jahr'))\n nr=int(self.LeseNummer())\n\n anzahl_dict = {}\n \n wert_s = vertrieb_dict.get('beitrag_RentenZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n anzahl_dict['beitragZumMarkt'] = wert_s\n \n anzahl_dict['erwaerteteAnzahl'] = self.erwarteteAnzahlRente\n \n wert_s = vertrieb_dict.get('provision_RentenZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n anzahl_dict['provisionZumMarkt'] = wert_s\n \n anzahl_dict['streuungImNG'] = self.streuungImNG\n \n if vertrieb_dict.get('neugeschaeft_Rente') == True:\n anzahl_renten = self.ErmittleAnzahl(anzahl_dict)\n else:\n anzahl_renten = 0\n \n if anzahl_renten > 0:\n tkz='20200101767'\n sra='N'\n beginn = str(jahr)+'0701'\n vertriebsnummer='007'\n zw=12\n nr=nr+1\n satz_dict['nr']=nr\n satz_dict['jahr']=jahr\n satz_dict['tkz']=tkz\n \n satz_dict['name']='tkz'\n satz_dict['wert']=tkz\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='sra'\n satz_dict['wert']=sra\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='beginn'\n satz_dict['wert']=beginn\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='anzahl'\n satz_dict['wert']=anzahl_renten\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='laufzeit'\n laufzeit = int(vertrieb_dict.get('laufzeitRente'))\n satz_dict['wert']=laufzeit\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n ende = str(jahr+laufzeit)+'0631'\n satz_dict['name']='ende'\n satz_dict['wert']=ende\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='vertriebsnummer'\n satz_dict['wert']=vertriebsnummer\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='zw'\n satz_dict['wert']=zw\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name'] = 'beitragsniveau'\n wert_s = vertrieb_dict.get('beitrag_RentenZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n satz_dict['wert'] = wert_s\n self.SchreibeInTabelleVertrieb(satz_dict)\n \n satz_dict['name'] = 'provisionsniveau'\n wert_s = vertrieb_dict.get('provision_RentenZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n satz_dict['wert'] = wert_s\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name'] = 'provisionMarkt'\n wert_s = self.provisionMarktRente\n wert_f = float(wert_s)\n wert_s = str(wert_f)\n satz_dict['wert'] = wert_s\n self.SchreibeInTabelleVertrieb(satz_dict)\n \n wert_s = vertrieb_dict.get('beitrag_BuZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n anzahl_dict['beitragZumMarkt'] = wert_s\n \n anzahl_dict['erwaerteteAnzahl'] = self.erwarteteAnzahlBu\n \n wert_s = vertrieb_dict.get('provision_BuZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n anzahl_dict['provisionZumMarkt'] = wert_s\n \n anzahl_dict['streuungImNG'] = self.streuungImNG\n \n if vertrieb_dict.get('neugeschaeft_Bu') == True:\n anzahl_bu = self.ErmittleAnzahl(anzahl_dict)\n else:\n anzahl_bu = 0\n\n if anzahl_bu > 0:\n tkz='20200101709'\n sra='N'\n beginn = str(jahr)+'0701'\n vertriebsnummer='007'\n zw=12\n nr=nr+1\n \n satz_dict['nr']=nr\n satz_dict['jahr']=jahr\n satz_dict['tkz']=tkz\n \n satz_dict['name']='tkz'\n satz_dict['wert']=tkz\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='sra'\n satz_dict['wert']=sra\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='beginn'\n satz_dict['wert']=beginn\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='anzahl'\n satz_dict['wert']=anzahl_bu\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='laufzeit'\n laufzeit = int(vertrieb_dict.get('laufzeitBu'))\n satz_dict['wert']=laufzeit\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n ende = str(jahr+laufzeit)+'0631'\n satz_dict['name']='ende'\n satz_dict['wert']=ende\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='vertriebsnummer'\n satz_dict['wert']=vertriebsnummer\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name']='zw'\n satz_dict['wert']=zw\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name'] = 'beitragsniveau'\n wert_s = vertrieb_dict.get('beitrag_BuZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n satz_dict['wert'] = wert_s\n self.SchreibeInTabelleVertrieb(satz_dict)\n\n satz_dict['name'] = 'provisionsniveau'\n wert_s = vertrieb_dict.get('provision_BuZumMarkt')\n wert_f = float(wert_s)/100\n wert_s = str(wert_f)\n satz_dict['wert'] = wert_s\n self.SchreibeInTabelleVertrieb(satz_dict)\n \n satz_dict['name'] = 'provisionMarkt'\n wert_s = self.provisionMarktBu\n wert_f = float(wert_s)\n wert_s = str(wert_f)\n satz_dict['wert'] = wert_s\n self.SchreibeInTabelleVertrieb(satz_dict)\n","repo_name":"KaMusialik/MeinSpiel","sub_path":"vertrieb.py","file_name":"vertrieb.py","file_ext":"py","file_size_in_byte":13096,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15304606574","text":"import subprocess\nimport os\nimport itertools\n\n#epochs = [80, 70, 60, 50, 40, 30, 20, 10]\nepochs = [5, 4, 3]\neval_types = ['hits@1', 'f1']\nprod = itertools.product(epochs, eval_types)\ntemplate = \"python3 convai_evaluation.py --model_checkpoint runs/run_e{:02} --eval_type {} --log_path logs/{}_e{:02}.txt\"\n\n#subprocess.run(template.format(80, 'ppl', 'ppl', 80).split())\nsubprocess.run(template.format(5, 'ppl', 'ppl', 5).split())\n\nfor epoch, eval_type in prod:\n command = template.format(epoch, eval_type, eval_type, epoch)\n subprocess.run(command.split())\n","repo_name":"machinereading/persona-chat","sub_path":"huggingface/evals.py","file_name":"evals.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"38755033892","text":"import numpy as np\nfrom .obb_nms import (single_obb_nms, single_poly_nms)\n\ndef obb_nms(bboxes, scores, iou_thr, score_thr, max_num=-1, small_thr=1e-6, mode=\"obb\"):\n assert bboxes.ndim == 2 and scores.ndim == 1\n bboxes = bboxes.astype(np.float64)\n scores = scores.astype(np.float64)\n\n if len(bboxes) == 0:\n return np.empty((0, ), dtype=np.int64)\n else:\n if mode == \"obb\":\n areas = bboxes[:, 2] * bboxes[:, 3]\n elif mode == \"poly\":\n areas = (np.max(bboxes[:, 0::2]) - np.min(bboxes[:, 0::2])) \\\n * (np.max(bboxes[:, 1::2]) - np.min(bboxes[:, 1::2])) / 2\n else:\n raise NotImplementedError\n filter_mask = np.bitwise_and((scores > score_thr), (areas > small_thr))\n filter_inds = np.nonzero(filter_mask)[0]\n _scores = scores[filter_inds]\n _bboxes = bboxes[filter_inds]\n\n num_to_keep = 0\n orders = np.argsort(_scores)[::-1]\n num_dets = len(_bboxes)\n suppress = np.zeros(num_dets, dtype=np.uint8)\n keeps = np.zeros(num_dets, dtype=np.int64)\n\n for i in range(num_dets):\n index_i = orders[i]\n if suppress[index_i] == 1:\n continue\n keeps[num_to_keep] = index_i\n num_to_keep += 1\n for j in range(i + 1, num_dets):\n index_j = orders[j]\n if suppress[index_j] == 1:\n continue\n if mode == \"obb\":\n ovr = single_obb_nms(_bboxes[index_i], _bboxes[index_j])\n elif mode == \"poly\":\n ovr = single_poly_nms(_bboxes[index_i], _bboxes[index_j])\n if ovr >= iou_thr:\n suppress[index_j] = 1\n \n keeps = filter_inds[keeps[:num_to_keep]]\n if max_num > 0:\n keeps = keeps[:max_num]\n\n return keeps\n ","repo_name":"DDGRCF/tzb-tools","sub_path":"model_merge/utils/obb_nms/obb_nms_wrapper.py","file_name":"obb_nms_wrapper.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20102054889","text":"class SegmentTree:\n def __init__(self, n, op, e):\n self.n = n\n self.op = op\n self.e = e\n self.size = 2 ** ((n - 1).bit_length())\n self.node = [self.e] * (2 * self.size)\n\n def __getitem__(self, i):\n return self.node[i + self.size]\n\n def __setitem__(self, i, val):\n i += self.size\n self.node[i] = val\n while i > 1:\n i >>= 1\n self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])\n\n def build(self, array):\n for i, val in enumerate(array, self.size):\n self.node[i] = val\n for i in range(self.size - 1, 0, -1):\n self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])\n\n def all_fold(self):\n return self.node[1]\n\n def fold(self, l, r):\n l, r = l + self.size, r + self.size\n vl, vr = self.e, self.e\n while l < r:\n if l & 1:\n vl = self.op(vl, self.node[l])\n l += 1\n if r & 1:\n r -= 1\n vr = self.op(self.node[r], vr)\n l, r = l >> 1, r >> 1\n return self.op(vl, vr)\n\n def max_right(self, l, f):\n if l == self.n:\n return self.n\n l += self.size\n v = self.e\n init = True\n while init or (l & -l) != l:\n init = False\n while l % 2 == 0:\n l >>= 1\n if not f(self.op(v, self.node[l])):\n while l < self.size:\n l <<= 1\n if f(self.op(v, self.node[l])):\n v = self.op(v, self.node[l])\n l += 1\n return l - self.size\n v = self.op(v, self.node[l])\n l += 1\n return self.n\n","repo_name":"Neterukun1993/Library","sub_path":"DataStructure/SegmentTree/SegmentTree.py","file_name":"SegmentTree.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"39548772268","text":"r\"\"\"\n.. _kgof:\n\nKernel Goodness-of-Fit Testing\n*********************\n\nThis notebook will introduce usage of kgof, a kernel goodness-of-fit hyppo package \nimplementing a linear time kernel-based GoF test.\n\nGiven a known probability density :math: `p` (model) and a sample \n:math: `\\{ \\mathbf{x}_i \\}_{i=1}^n \\sim q` where :math:`q` is an unknown \ndensity, a goodness-of-fit test proposes null and alternative hypotheses:\n\n.. math::\n\n H_0 &: p = q \\\\\n H_1 &: p \\neq q\n\nIn other words, the GoF test tests whether or not the sample :math: `\\{ \\mathbf{x}_i \\}_{i=1}^n` \nis distributed according to a known :math:`p`.\n\nThe implemented test relies on a new test statistic called The Finite-Set Stein Discrepancy (FSSD) \nwhich is a discrepancy measure between a density and a sample. Unique features of the new goodness-of-fit test are:\n\nIt makes only a few mild assumptions on the distributions :math: `p` and :math: `q`. The model :math: `p` \ncan take almost any form. The normalizer of :math: `p` is not assumed known. The test only assesses the goodness of \n:math: `p` through :math: `\\nabla_{\\mathbf{x}} \\log p(\\mathbf{x})` i.e., the first derivative of the log density.\n\nThe runtime complexity of the full test (both parameter tuning and the actual test) is \n:math: `\\mathcal{O}(n)` i.e., linear in the sample size.\n\nIt returns a set of points (features) which indicate where :math: `p` fails to fit the data.\n\nFor demonstration purposes, let us consider a simple two-dimensional problem where :math: `p` \nis the standard Gaussian.\n\"\"\"\n\n########################################################################################\n# .. _gauss fssd:\n#\n# A simple Gaussian model\n# ---------------------------------------------\n#\n# Assume that :math: `p(\\mathbf{x}) = \\mathcal{N}(\\mathbf{0}, \\mathbf{I})`\n# in :math: `\\mathbb{R}^2` (two-dimensional space).\n# The data :math: `\\{ \\mathbf{x}_i \\}_{i=1}^n \\sim q = \\mathcal{N}([m, 0], \\mathbf{I})`\n# where :math: `m` specifies the mean of the first coordinate of :math: `q`.\n# From this setting, if :math: `m\\neq 0`, then :math: `H_1` is true and the test should\n# reject :math: `H_0`.\n# First construct the log density function for the model\n\nimport data \nimport density\nfrom gaussfssd import GaussFSSD\nimport kernel \nimport util\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport autograd.numpy as np\nimport scipy.stats as stats\n\ndef isogauss_log_den(X):\n mean = np.zeros(2)\n variance = 1\n unden = -np.sum((X - mean)**2, 1) / (2.0 * variance)\n return unden\n\n########################################################################################\n# This function computes the log of an unnormalized density. This works fine as this test\n# only requires a :math: `nabla_{\\mathbf{x}} \\log p(\\mathbf{x})` which does not depend on \n# the normalizer. The gradient :math: `\\nabla_{\\mathbf{x}} \\log p(\\mathbf{x})` will be \n# automatically computed by autograd. In this kgof package, a model :math: `p` can be \n# specified by implementing the class :class: `hyppo.kgof.density.UnnormalizedDensity`. Implementing\n# this directly is a bit tedious, however. An easier way is to use the function \n# :function: `hyppo.kgof.density.from_log_den(d, f)` which takes 2 arguments as inputs ``d``, \n# the dimension of the input space, and ``f``, a function\n# taking in a 2D numpy array of size :math: `n` x :math: `d` and producing a one-dimensional array\n# of size :math: `n` for the :math: `n` values of the log unnormalized density.\n# Construct an :class: `UnnormalizedDensity` which will represent a Gaussian model. All the implemented\n# goodness-of-fit tests take this object as input.\n\np = density.from_log_den(2, isogauss_log_den) # UnnormalizedDensity object\n\n# Next, draw a sample from q.\n# Drawing n points from q\nm = 1 # If m = 0, p = q and H_0 is true\n\nseed = 4\nnp.random.seed(seed)\nn = 400\nX = np.random.randn(n, 2) + np.array([m, 0])\n\n# Plot the data from q\nplt.plot(X[:, 0], X[:, 1], 'ko', label='Data from $q$')\nplt.legend()\n\n########################################################################################\n# All the implemented tests take the data in the form of a :class: `hyppo.kgof.data.Data` object. \n# This is just an encapsulation of the sample :math: `X`. To construct :class: `data.Data` do the following:\n\n# dat will be fed to the test.\ndat = data.Data(X) # Creates a fssdgof Data object here\n\n########################################################################################\n# Now that the data has been generated, randomly split it into two disjoint halves: ``train`` and ``test``. \n# The training set ``train`` will be used for parameter optimization. The testing set ``test`` will be used \n# for the actual goodness-of-fit ``test``. ``train``` and ``test`` are again of type :class: `data.Data`.\n\ntrain, test = dat.split_tr_te(tr_proportion=0.2, seed=2)\n\n# Optimize the parameters of the test on train. The optimization relies on autograd to compute the gradient. \n# A Gaussian kernel is being used for the test.\n\n# J is the # of test locs (features), not larger than 10\nJ = 1\n\nopts = {\n 'reg': 1e-2, # regularization parameter in the optimization objective\n 'max_iter': 50, # maximum number of gradient ascent iterations\n 'tol_fun':1e-7, # termination tolerance of the objective\n}\n\n# make sure to give train (NOT test).\n# do the optimization with the options in opts.\nV_opt, gw_opt, opt_info = GaussFSSD.optimize_auto_init(p, train, J, **opts)\n\n########################################################################################\n# The optimization procedure returns --\n# .. note::\n#\n# V_opt: optimized test locations (features). A :math:`J \\times d` ``numpy`` array.\n# gw_opt: optimized Gaussian width (for the Gaussian kernel). A floating point number.\n# opt_info: a dictionary containing information gathered during the optimization.\n\nopt_info\n\n########################################################################################\n# Use these optimized parameters to construct the FSSD test. The test using a Gaussian \n# kernel is implemented in :class: `hyppo.kgof.goftest.GaussFSSD`.\n\nalpha = 0.01 # significance level of the test (99% confidence)\nfssd_opt = GaussFSSD(p, gw_opt, V_opt, alpha)\n\n# Perform the goodness-of-fit test on the testing data test.\n# return a dictionary of testing results\ntest_result = fssd_opt.test(test)\ntest_result\n\n########################################################################################\n# It can be seen that the test correctly rejects :math:`H_0` with a very small p-value.\n\n########################################################################################\n#\n# Important note\n# ---------------------------------------------\n#\n# A few points worth mentioning\n#\n# The FSSD test requires that the derivative of :math: `\\log p` exists.\n# The test requires a technical condition called the \"vanishing boundary\" condition for it to be consistent. \n# The condition is :math: `\\lim_{\\|\\mathbf{x} \\|\\to \\infty} p(\\mathbf{x}) \\mathbf{g}(\\mathbf{x}) = \\mathbf{0}` where \n# :math: `\\mathbf{g}` is the so called the Stein witness function which depends on the kernel and \n# :math: `\\nabla_{\\mathbf{x}} \\log p(\\mathbf{x})`. For a density :math: `p` which has support everywhere e.g., \n# Gaussian, there is no problem at all. \n# However, for a density defined on a domain with a boundary, one has to be careful. For example, if :math: `p` is a \n# Gamma density defined on the positive orthant of :math: `\\mathbb{R}`, the density itself can actually be evaluated on negative points. \n# Looking at the way the Gamma density is written, there is nothing that tells the test that it cannot be evaluated on negative orthant. \n# Therefore, if :math: `p` is Gamma, and the observed sample also follows :math: `p` \n# (i.e., :math:`H_0` is true), the test will still reject :math:`H_0`! \n# The reason is that the data do not match the left tail (in the negative region!) of the Gamma. \n# It is necessary to include the fact that negative region has 0 density into the density itself.\n\n","repo_name":"NeuroDataDesign/hyppo-2021-2022","sub_path":"darsh_patel/figure_code/fssdgof/kgof.py","file_name":"kgof.py","file_ext":"py","file_size_in_byte":8027,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"1052814414","text":"#!/bin/env python\r\nimport re, io, os, csv, zipfile, codecs, subprocess, rdflib, logging\r\nfrom geotext import GeoText\r\nfrom collections import namedtuple\r\n\r\nARCHIVES_PATH = 'archive/root/zipfiles'\r\nIS_DEBUG = False\r\nUSE_GEOTEXT = 'GEOTEXT'\r\nUSE_SPACY = 'SPACY'\r\nBOOKS_CSV = 'books.csv'\r\nCITIES_CSV = 'mentions.csv'\r\n\r\n#Book class. Contains metadata, full text and list of cities when populated.\r\nclass PGBook:\r\n def __init__(self, bookID):\r\n self.bookID = bookID\r\n self.author = 'N/A'\r\n self.title = 'N/A'\r\n self.bookText = 'N/A'\r\n self.cities = []\r\n\r\n def prettyPrint(self):\r\n print(self.bookID)\r\n print('\\t' + self.author)\r\n print('\\t' + self.title)\r\n print(self.cities)\r\n print('-:_:-:-:_:-:-:_:-:-:_:-')\r\n\r\n def __str__(self):\r\n return str(self.bookID) + ': ' + str(self.title) + ', by ' + str(self.author) + \".\\ncities: \" + str(self.cities) \r\n\r\n#A named tuple for transport of CSV file pointers\r\nFileTuple = namedtuple('FileTuple', ['books', 'cities'])\r\n\r\n\r\ndef traverseArchive(fileTuple):\r\n errorCount = 3000\r\n folderPath = 'archive/root/zipfiles'\r\n for fileName in os.listdir(folderPath):\r\n zipFilePath = folderPath + '/' + fileName\r\n with zipfile.ZipFile(zipFilePath, 'r') as archive:\r\n for innerFileName in archive.namelist():\r\n if innerFileName.endswith('.txt'):\r\n print(innerFileName)\r\n bookID = os.path.splitext(innerFileName)[0]\r\n try:\r\n #archive.testzip()\r\n #parseText(codecs.encode(archive.read(innerFileName), 'utf-8'))\r\n myBook = unzipAndParse(zipFilePath, innerFileName)\r\n appendCSV(myBook, fileTuple)\r\n except NotImplementedError:\r\n print(\"NotImplementedError. Possibly wrong compression, Trying System call\")\r\n #unzipAndParse(zipFilePath ,innerFileName)\r\n errorCount += 1\r\n except IndexError:\r\n print('Unexpected first line.')\r\n errorCount += 10000\r\n print(str(errorCount) + ' archives could not be opened.')\r\n\r\n\r\ndef unzipAndParse(filePath, innerFile):\r\n bookID = os.path.splitext(innerFile)[0]\r\n myBook = PGBook(bookID)\r\n myBook.bookText = subprocess.check_output(['unzip', '-p', filePath, innerFile])\r\n myBook.cities = parseCities(myBook.bookText)\r\n myBook = getMetadataFromRDF(myBook)\r\n myBook.prettyPrint()\r\n return myBook\r\n #print(str(myBook))\r\n #parseText(bookID, subprocess.check_output(['unzip', '-p', filePath, innerFile]))\r\n\r\n\r\ndef tryParseMetadata(book):\r\n book.author = parseAuthor(book.bookText)\r\n book.title = parseTitle(book.bookText)\r\n return book\r\n\r\n\r\n#DEPRECATED\r\ndef parseText(bookID, bookText):\r\n author = ''\r\n title = ''\r\n try:\r\n author = parseAuthor(bookText)\r\n title = parseTitle(bookText)\r\n except IndexError:\r\n print(\"Could not extract metadata from text...\")\r\n\r\n printBookInfo(author, title, parseCities(bookText))\r\n\r\n\r\n#DEPRECATED.\r\ndef parseAuthor(bookText):\r\n authorTitle = bookText.split('\\n')[0].split(' of ', 1)[1]\r\n return authorTitle.split(', by ')[1]\r\n\r\n\r\n#DEPRECATED.\r\ndef parseTitle(bookText):\r\n authorTitle = bookText.split('\\n')[0].split(' of ', 1)[1]\r\n return authorTitle.split(', by ')[0]\r\n\r\n\r\n#DEPRECATED\r\ndef printBookInfo(author, title, cities):\r\n print('\\n' + author + \" - \" + title)\r\n print(cities)\r\n print('\\n\\n')\r\n\r\n\r\ndef parseCities(bookText, method=USE_GEOTEXT):\r\n if method == USE_GEOTEXT:\r\n return parseCitiesGeoText(bookText)\r\n elif method == USE_SPACY:\r\n return parseCitiesSpacy(bookText)\r\n else:\r\n raise NotImplementedError('No such parsing method found')\r\n\r\n\r\ndef parseCitiesGeoText(bookText):\r\n return GeoText(bookText).cities\r\n\r\n\r\n#NOT IMPLEMENTED\r\ndef parseCitiesSpacy():\r\n raise NotImplementedError('This function has not been implemented.')\r\n\r\n\r\ndef getMetadataFromRDF(book):\r\n if not isinstance(book, PGBook):\r\n raise TypeError('Argument(book) must be an instance of PGBook!')\r\n\r\n fileName = 'rdf-files/cache/epub/' + str(book.bookID) + '/pg' + str(book.bookID) + '.rdf'\r\n g = rdflib.Graph()\r\n \r\n try: #RDF file may not exist\r\n g.parse(fileName)\r\n except IOError:\r\n print('RDF archive for ' + book.bookID + ' not found. Has the whole archive been correctly decompressed?')\r\n print('Trying to parse metadata directly from book Text')\r\n return tryParseMetadata(book)\r\n\r\n\r\n for s, p, o in g:\r\n printFlag = False\r\n \r\n if '/pgterms/name' in p.encode('utf-8'):\r\n book.author = o.encode('utf-8')\r\n printFlag = True\r\n elif '/dc/terms/title' in str(p.encode('utf-8')):\r\n book.title = o.encode('utf-8')\r\n printFlag = True\r\n print(o.encode('utf-8'))\r\n\r\n if printFlag and IS_DEBUG and False:\r\n print('s: ' + s.encode('utf-8') + '\\np:\\t' + p.encode('utf-8') + '\\no:\\t\\t' + o.encode('utf-8'))\r\n\r\n return book\r\n\r\n\r\n\r\ndef initCSV():\r\n bookHeader = ['bookID', 'author', 'title']\r\n with open(BOOKS_CSV, 'w') as file:\r\n writer = csv.writer(file)\r\n writer.writerow(bookHeader)\r\n\r\n cityHeader = ['bookID', 'city']\r\n with open(CITIES_CSV, 'w') as file:\r\n writer = csv.writer(file)\r\n writer.writerow(cityHeader)\r\n\r\n\r\ndef appendCSV(book, fileTuple):\r\n if not isinstance(book, PGBook):\r\n raise TypeError('Argument(book) must be an instance of PGBook!')\r\n\r\n bookFields = [book.bookID, book.author, book.title]\r\n bWriter = csv.writer(fileTuple.books)\r\n bWriter.writerow(bookFields)\r\n\r\n for city in book.cities:\r\n cityFields = [book.bookID, city]\r\n \r\n cWriter = csv.writer(fileTuple.cities)\r\n cWriter.writerow(cityFields)\r\n\r\n\r\n\r\n#Start going over files:\r\ninitCSV()\r\n\r\nwith open(BOOKS_CSV, 'a') as booksFile, open(CITIES_CSV, 'a') as citiesFile:\r\n fileTuple = FileTuple(booksFile, citiesFile)\r\n traverseArchive(fileTuple)\r\n\r\n#myBook = PGBook(1644)\r\n#print(str(myBook))\r\n#myBook = getMetadataFromRDF(PGBook(1644))\r\n#print(str(myBook))\r\n\r\n","repo_name":"DatabaseGroup9/PGParser","sub_path":"parseArchive.py","file_name":"parseArchive.py","file_ext":"py","file_size_in_byte":6317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41306921391","text":"from Agent import *\n\nclass LexicographicAgent(Agent):\n\n def __init__(self, gameManager, verbose=False, seeCode=False, firstGuess = makeCode([1,1,2,2])):\n Agent.__init__(self, gameManager, verbose, seeCode)\n self.firstGuess = firstGuess\n self.allCodes = [Code(pinlist) for pinlist in generateAllCodes()]\n self.numberOfCodes = len(self.allCodes)\n self.currentIndex = -1\n self.isFirstGuess = True\n\n def createGuess(self):\n # starts with a given first guess, then just guesses codes in lexicographic order (ignoring inconsistent codes)\n # Based on Swaszek (1999-2000)\n if self.isFirstGuess:\n self.isFirstGuess = False\n return self.firstGuess\n else:\n for i in range(self.currentIndex+1, self.numberOfCodes):\n codeToCheck = self.allCodes[i]\n if self.isConsistent(codeToCheck):\n self.currentIndex = i\n return codeToCheck","repo_name":"lprehn/MasterMind","sub_path":"Agents/LexicographicAgent.py","file_name":"LexicographicAgent.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2223026288","text":"# zum ausführen in der powerchell \"python .\\ip_validation.py 128.80.86.125\" 128.80.86.125 da kann man jede ip adresse eingeben die überprüft werden soll.\n# Python Datei: ip_validation.py\n# Autor: Andreas Kort\n# Split-Validierung in Python hinzugefügt überprüfen ob 4 Elemente sind und Ip adresse im Terminal eingeben Version 3\n\nimport sys # Importiere das sys-Modul, um die Argumente aus der Bash-Umgebung zu erhalten wenn nicht vorhanden. \n\n# Beschriebene Funktion\n# In den () können Parameter eingesetzt werden, in diesem Fall nicht nötig.\ndef split_numbers(ip_string):\n numbers = ip_string.split(\".\")\n return [int(number) for number in numbers]\n# .split splittet den ip_string an den Stellen \".\" und löst so die Strings auf.\n# Mit int(number) for number in numbers und int() überarbeiten wir die Strings in Ganzzahlen, die dann mit , geteilt werden.\n# Danach werden die Strings \"\" entfernt und in der IP-Variable 128, 80, 86, 125 gespeichert und ausgegeben.\n# Neue Funktion check_numbers einbauen\ndef check_numbers(numbers_list):\n # Überprüfe, ob genau 4 Elemente vorhanden sind, wenn ja gut, wenn nein, falsch\n if len(numbers_list) != 4:\n return False\n\n # Überprüfe, ob jedes Element zwischen 0 und 255 ist\n for number in numbers_list:\n if not (0 <= number <= 255):\n return False\n\n return True\n\nif __name__ == \"__main__\":\n # Erhalte das Argument von der Bash-Umgebung mit sys.argv[1]\n ip_string = sys.argv[1]\n \n # Rufe die Funktion split_numbers mit dem übergebenen Argument auf\n ip_numbers = split_numbers(ip_string)\n print(ip_numbers)\n\n # Rufe die Funktion check_numbers mit dem Ergebnis von split_numbers auf\n result = check_numbers(ip_numbers)\n print(result)\n\n","repo_name":"AndreasKort/API","sub_path":"split_numbers.py","file_name":"split_numbers.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"8181516169","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport argparse\nimport json\nimport sys\nimport os\nimport os.path\nfrom tqdm import tqdm\nfrom datetime import datetime\nfrom io import open\nfrom inscrawler import InsCrawler\nfrom inscrawler.settings import override_settings\nfrom inscrawler.settings import prepare_override_settings\nfrom inscrawler.utils import *\ndef usage():\n return \"\"\"\n python crawler.py posts -u cal_foodie -n 100 -o ./output\n python crawler.py posts_full -u cal_foodie -n 100 -o ./output\n python crawler.py profile -u cal_foodie -o ./output\n python crawler.py profile_script -u cal_foodie -o ./output\n python crawler.py hashtag -t taiwan -o ./output\n The default number for fetching posts via hashtag is 100.\n \"\"\"\ndef get_posts_by_user(username, number, detail, debug):\n ins_crawler = InsCrawler(has_screen=debug)\n return ins_crawler.get_user_posts(username, number, detail)\ndef get_profile(username):\n ins_crawler = InsCrawler()\n return ins_crawler.get_user_profile(username)\ndef get_profile_from_script(username):\n ins_cralwer = InsCrawler()\n return ins_cralwer.get_user_profile_from_script_shared_data(username)\ndef get_posts_by_hashtag(tag, number, debug):\n ins_crawler = InsCrawler(has_screen=debug)\n return ins_crawler.get_latest_posts_by_tag(tag, number)\ndef jieun(debug):\n ins_crawler = InsCrawler(has_screen=debug)\n return ins_crawler.jieun()\ndef hankyul(debug):\n ins_crawler = InsCrawler(has_screen=debug)\n return ins_crawler.hankyul()\ndef cheol(debug):\n ins_crawler = InsCrawler(has_screen=debug)\n return ins_crawler.cheol()\ndef arg_required(args, fields=[]):\n for field in fields:\n if not getattr(args, field):\n parser.print_help()\n sys.exit()\ndef check_for_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\ndef output(data, type):\n filepath = \"../data/instagram/\" + datetime.today().strftime('%Y-%m-%d') + \"/\"\n fileName = \"instagram_ver_\"+datetime.today().strftime('%Y_%m_%d_%H_%M_%S') + \"_\" + type + \".json\"\n check_for_dir(filepath)\n with open(filepath+fileName, \"w\", encoding=\"utf8\") as f:\n json.dump(data, f, indent=4, ensure_ascii=False)\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Instagram Crawler\", usage=usage())\n parser.add_argument(\n \"mode\", help=\"options: [posts, posts_full, profile, profile_script, hashtag, parse_img_tag]\"\n )\n parser.add_argument(\"-n\", \"--number\", type=int, help=\"number of returned posts\")\n parser.add_argument(\"-u\", \"--username\", help=\"instagram's username\")\n parser.add_argument(\"-t\", \"--tag\", help=\"instagram's tag name\")\n parser.add_argument(\"-o\", \"--output\", help=\"output file name(json format)\")\n parser.add_argument(\"-p\", \"--part\", help=\"region part\")\n parser.add_argument(\"--debug\", action=\"store_true\")\n prepare_override_settings(parser)\n args = parser.parse_args()\n override_settings(args)\n if args.mode in [\"posts\", \"posts_full\"]:\n arg_required(\"username\")\n output(\n get_posts_by_user(\n args.username, args.number, args.mode == \"posts_full\", args.debug\n ),\n args.output,\n )\n elif args.mode == \"profile\":\n arg_required(\"username\")\n output(get_profile(args.username), args.output)\n elif args.mode == \"profile_script\":\n arg_required(\"username\")\n output(get_profile_from_script(args.username), args.output)\n elif args.mode == \"hashtag\":\n arg_required(\"part\")\n for rest in tqdm(get_restaurant_foodcategory_list(int(args.part))):\n tag = rest['상호명']\n post_detail, user_detail, post_set, user_set = get_posts_by_hashtag(tag, args.number or 10, args.debug)\n if len(post_detail) == 0:\n continue\n output(post_detail, tag+\"_post_detail\")\n output(user_detail, tag+\"_user_detail\")\n output(list(post_set), tag+\"_post_set\")\n output(list(user_set), tag+\"_user_set\")\n elif args.mode == \"jieun\":\n jieun(args.debug)\n elif args.mode == \"hankyul\":\n hankyul(args.debug)\n elif args.mode == \"cheol\":\n cheol(args.debug)\n else:\n usage()\n","repo_name":"hankyul-needs-girfriends/woowa-crawler","sub_path":"instagram-crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16366763926","text":"from PyQt5.QtCore import Qt, QDate\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import QDialog, QHeaderView, QTableWidgetItem, QMessageBox, QDateEdit\nfrom sysManage.component import getMessageBox\n\nfrom database.contractManagementSql import *\nfrom widgets.contractMangement.attachmentDialogUI import AttachmentDialogUI\n\n\nclass AttachmentDialog(QDialog, AttachmentDialogUI):\n def __init__(self, parent=None):\n super(AttachmentDialog, self).__init__(parent)\n self.setupUi(self)\n self.setWindowIcon(QIcon(\":/pic/system.png\"))\n self.resultList = []\n self.maintenanceId = -1\n self.currentLastRow = -1\n self.year = ''\n self.signalConnection()\n\n\n\n def signalConnection(self):\n self.pb_add.clicked.connect(self.soltAdd)\n self.pb_delete.clicked.connect(self.soltDelete)\n self.tw_result.itemChanged.connect(self.slotAlterAndSava)\n\n def initTableWidget(self, maintenanceId,year):\n self.maintenanceId = maintenanceId\n self.year = year\n self.resultList = getAttachmentInformation(maintenanceId,year)\n self.initHeader()\n if len(self.resultList) != 0:\n self.displayData()\n\n def initHeader(self):\n self.tw_result.setRowCount(2 + len(self.resultList))\n self.tw_result.setColumnCount(18)\n self.tw_result.verticalHeader().setVisible(False)\n self.tw_result.horizontalHeader().setVisible(False)\n # self.tw_result.setEditTriggers(QTableWidget.NoEditTriggers)\n self.tw_result.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)\n self.tw_result.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n self.tw_result.resizeColumnsToContents()\n self.tw_result.resizeRowsToContents()\n # 绘制表头\n item = QTableWidgetItem(\"XX装备维修免税清单明细表\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(0, 0, item)\n self.tw_result.setSpan(0, 0, 1, 18)\n\n item = QTableWidgetItem(\"序号\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 0, item)\n\n item = QTableWidgetItem(\"合同号\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 1, item)\n\n item = QTableWidgetItem(\"合同名称\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 2, item)\n\n item = QTableWidgetItem(\"计划项目\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 3, item)\n\n item = QTableWidgetItem(\"预算金额\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 4, item)\n\n item = QTableWidgetItem(\"单价(万元)\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 5, item)\n\n item = QTableWidgetItem(\"数量/(单位)\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 6, item)\n\n item = QTableWidgetItem(\"预算(万元)\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 7, item)\n\n item = QTableWidgetItem(\"当年应付\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 8, item)\n\n item = QTableWidgetItem(\"签订日期\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 9, item)\n\n item = QTableWidgetItem(\"甲方单位\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 10, item)\n\n item = QTableWidgetItem(\"单位性质\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 11, item)\n\n item = QTableWidgetItem(\"纳税人识别号\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 12, item)\n\n item = QTableWidgetItem(\"乙方单位\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 13, item)\n\n item = QTableWidgetItem(\"付款单位\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 14, item)\n\n item = QTableWidgetItem(\"计划文件\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 15, item)\n\n item = QTableWidgetItem(\"交付日期\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 16, item)\n\n item = QTableWidgetItem(\"备注\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(1, 17, item)\n\n\n def displayData(self):\n self.tw_result.itemChanged.disconnect(self.slotAlterAndSava)\n self.resultList = getAttachmentInformation(self.maintenanceId, self.year)\n for i in range(len(self.resultList)):\n item = QTableWidgetItem(str(self.resultList[i][1]))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 0, item)\n\n item = QTableWidgetItem(self.resultList[i][2]) #no\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 1, item)\n\n item = QTableWidgetItem(self.resultList[i][3]) #name\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 2, item)\n\n item = QTableWidgetItem(self.resultList[i][4]) # plan_project\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 3, item)\n\n item = QTableWidgetItem(str(self.resultList[i][5]))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 4, item)\n\n item = QTableWidgetItem(str(self.resultList[i][6]))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 5, item)\n\n item = QTableWidgetItem(str(self.resultList[i][7]))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 6, item)\n\n item = QTableWidgetItem(str(self.resultList[i][8]))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 7, item)\n\n item = QTableWidgetItem(str(self.resultList[i][9]))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 8, item)\n\n date = self.resultList[i][10]\n parsedDateList = date.split('-')\n dataEdit = QDateEdit()\n dataEdit.setDisplayFormat(\"yyyy-MM-dd\")\n dataEdit.setDate(QDate(int(parsedDateList[0]), int(parsedDateList[1]), int(parsedDateList[2])))\n dataEdit.setEnabled(False)\n self.tw_result.setCellWidget(2 + i, 9, dataEdit)\n\n item = QTableWidgetItem(self.resultList[i][11])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 10, item)\n\n item = QTableWidgetItem(self.resultList[i][12])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 11, item)\n\n item = QTableWidgetItem(self.resultList[i][13])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 12, item)\n\n item = QTableWidgetItem(self.resultList[i][14])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 13, item)\n\n item = QTableWidgetItem(self.resultList[i][15])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 14, item)\n\n item = QTableWidgetItem(self.resultList[i][16])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 15, item)\n\n date = self.resultList[i][17]\n parsedDateList = date.split('-')\n dataEdit = QDateEdit()\n dataEdit.setDisplayFormat(\"yyyy-MM-dd\")\n dataEdit.setDate(QDate(int(parsedDateList[0]),int(parsedDateList[1]),int(parsedDateList[2])))\n dataEdit.setEnabled(False)\n self.tw_result.setCellWidget(2 + i, 16, dataEdit)\n\n item = QTableWidgetItem(self.resultList[i][18])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n #item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2 + i, 17, item)\n self.tw_result.itemChanged.connect(self.slotAlterAndSava)\n\n\n def slotAlterAndSava(self):\n selectRow = self.tw_result.selectedItems()\n if len(selectRow) != 0:\n currentRow = selectRow[0].row()\n currentColumn = selectRow[0].column()\n if (currentColumn == 8 or currentColumn == 4 or currentColumn == 5 or currentColumn == 6 and currentRow >= 2):\n item0 = self.tw_result.item(currentRow, 5)\n item1 = self.tw_result.item(currentRow, 6)\n item2 = self.tw_result.item(currentRow, 4)\n item3 = self.tw_result.item(currentRow, 8)\n if (item1 != None and item0 != None and item2 != None and item3 != None):\n if (len(item0.text()) > 0 and len(item1.text()) > 0 and len(item2.text()) > 0 and len(item3.text()) > 0):\n self.tw_result.itemChanged.disconnect(self.slotAlterAndSava)\n count = 0\n unit = 0\n try:\n count = int(item1.text())\n except ValueError:\n getMessageBox(\"注意\", \"请输入整数!\", True, False)\n item1.setText('')\n try:\n unit = float(item0.text())\n except:\n item0.setText('')\n getMessageBox(\"注意\", \"请输入正确的数字!\", True, False)\n\n try:\n float(item2.text())\n except:\n item2.setText('')\n getMessageBox(\"注意\", \"请输入正确的数字!\", True, False)\n\n try:\n float(item3.text())\n except:\n item3.setText('')\n getMessageBox(\"注意\", \"请输入正确的数字!\", True, False)\n\n amount = round(count * unit, 6)\n if (amount != 0):\n item = self.tw_result.item(currentRow, 7)\n if (item != None):\n item.setText(str(amount))\n item.setFlags(Qt.ItemIsEnabled)\n else:\n item = QTableWidgetItem(str(amount))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(currentRow, 7, item)\n self.tw_result.itemChanged.connect(self.slotAlterAndSava)\n\n if currentRow == self.currentLastRow:\n self.savaRowData(currentRow)\n else:\n self.alterRowData(currentRow)\n\n\n\n def savaRowData(self,row):\n rowData = []\n rowData.append(str(self.maintenanceId))\n for i in range(self.tw_result.columnCount()):\n if i == 9 or i == 16:\n item = self.tw_result.cellWidget(row, i)\n if item != None:\n date = item.date().toString(Qt.ISODate)\n rowData.append(date)\n else:\n break\n else:\n item = self.tw_result.item(row, i)\n if (item != None):\n if (len(item.text()) > 0):\n rowData.append(item.text())\n else:\n break\n rowData.append(self.year)\n if len(rowData) == self.tw_result.columnCount() + 2:\n if (insertOneDataInToContractAttachment(rowData) == True):\n getMessageBox(\"注意\", \"插入成功!\", True, False)\n self.currentLastRow = -1\n else:\n getMessageBox(\"警告\", \"插入失败!\", True, False)\n self.displayData()\n\n def alterRowData(self, row):\n rowData = [str(self.maintenanceId)]\n for i in range(self.tw_result.columnCount()):\n if i == 9 or i == 16:\n item = self.tw_result.cellWidget(row,i)\n if item != None:\n date = item.date().toString(Qt.ISODate)\n rowData.append(date)\n else:\n break\n else:\n item = self.tw_result.item(row, i)\n if (item != None):\n if (len(item.text()) > 0):\n rowData.append(item.text())\n else:\n break\n rowData.append(self.year)\n if len(rowData) == self.tw_result.columnCount() + 2:\n if (updataOneDataToContractAttachment(rowData) == True):\n getMessageBox(\"注意\", \"修改成功!\", True, False)\n else:\n getMessageBox(\"警告\", \"修改失败!\", True, False)\n self.displayData()\n\n def soltAdd(self):\n if self.tw_result.rowCount() <= 2 + len(self.resultList):\n self.tw_result.itemChanged.disconnect(self.slotAlterAndSava)\n maintenceData = getContractMaintenanceInfoByMaintanceId(self.maintenanceId)\n rowCount = self.tw_result.rowCount()\n self.currentLastRow = rowCount\n self.tw_result.insertRow(rowCount)\n if (rowCount + 1 == 3):\n item = QTableWidgetItem('1')\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(2, 0, item)\n else:\n lastNo = int(self.tw_result.item(rowCount - 1,0).text())\n item = QTableWidgetItem(str(lastNo + 1))\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(rowCount, 0, item)\n\n #合同号\n item = QTableWidgetItem(maintenceData[2])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(rowCount, 1, item)\n\n #合同名称\n item = QTableWidgetItem(maintenceData[3])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(rowCount, 2, item)\n\n #预算金额\n # 合同名称\n item = QTableWidgetItem(\"\")\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(rowCount, 7, item)\n\n #签订日期\n date = maintenceData[9]\n parsedDateList = date.split('-')\n dataEdit = QDateEdit()\n dataEdit.setDisplayFormat(\"yyyy-MM-dd\")\n dataEdit.setDate(QDate(int(parsedDateList[0]), int(parsedDateList[1]), int(parsedDateList[2])))\n dataEdit.setEnabled(False)\n self.tw_result.setCellWidget(rowCount, 9, dataEdit)\n\n #甲方\n item = QTableWidgetItem(maintenceData[4])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(rowCount, 10, item)\n\n # 乙方\n item = QTableWidgetItem(maintenceData[5])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(rowCount, 13, item)\n\n date = maintenceData[-2]\n parsedDateList = date.split('-')\n dataEdit = QDateEdit()\n dataEdit.setDisplayFormat(\"yyyy-MM-dd\")\n dataEdit.setDate(QDate(int(parsedDateList[0]), int(parsedDateList[1]), int(parsedDateList[2])))\n dataEdit.setEnabled(False)\n self.tw_result.setCellWidget(rowCount, 16, dataEdit)\n\n item = QTableWidgetItem(maintenceData[-1])\n item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n item.setFlags(Qt.ItemIsEnabled)\n self.tw_result.setItem(rowCount, 17, item)\n\n self.tw_result.itemChanged.connect(self.slotAlterAndSava)\n else:\n getMessageBox(\"注意\", \"请先将数据补充完整!\", True, False)\n\n\n\n\n\n\n def soltDelete(self):\n rowCount = self.tw_result.currentRow()\n resultCount = len(self.resultList)\n if rowCount < 2:\n getMessageBox(\"注意\", \"请选中有效单元格!\", True, False)\n elif rowCount >= 2 and rowCount < 2 + resultCount:\n reply = getMessageBox('警告', '是否删除该行数据?', True, True)\n if reply == QMessageBox.Ok:\n print(self.resultList[rowCount - 2][0], self.resultList[rowCount - 2][1],self.year)\n deleteDataByContractAttachmentId(self.resultList[rowCount - 2][0], self.resultList[rowCount - 2][1],self.year)\n self.tw_result.removeRow(rowCount)\n else:\n self.tw_result.removeRow(rowCount)\n","repo_name":"Belos10/Equip","sub_path":"sysManage/contractMangement/AttachmentDialog.py","file_name":"AttachmentDialog.py","file_ext":"py","file_size_in_byte":19463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70518874198","text":"#!/usr/bin/env python3\n\"\"\"\nTakes in input from the user\n\"\"\"\n\n\nwhile 1:\n question = input(\"Q: \")\n words = [\"exit\", \"quit\", \"goodbye\", \"bye\"]\n\n if question.lower().strip() in words:\n print(\"A: Goodbye\")\n exit(0)\n else:\n print(\"A: \")\n","repo_name":"Kenneth-ca/holbertonschool-machine_learning","sub_path":"supervised_learning/0x13-qa_bot/1-loop.py","file_name":"1-loop.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"85"} +{"seq_id":"33971030365","text":"class Solution(object):\n def combinationSum2(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n\n candidates.sort()\n return self.adding(candidates, 0, target, [])\n\n def adding(self, candidates, startIndex, target, output):\n if target == 0:\n return [output]\n\n result = []\n for i in range(startIndex, len(candidates)):\n num = candidates[i]\n if num > target:\n break\n if i == startIndex or candidates[i-1] != num:\n result += self.adding(candidates, i + 1, target - num, output + [num])\n\n return result\n\nclass Solution2(object):\n def combinationSum2(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n\n return self.helper(sorted(candidates), target)\n\n def helper(self, candidates, target):\n if target == 0:\n return [[]]\n if not candidates:\n return []\n\n result = []\n prev = float('-inf')\n for i in range(len(candidates)):\n candidate = candidates[i]\n if candidate > target:\n break\n if prev != candidate:\n rhs = self.combinationSum2(candidates[i+1:], target-candidate)\n for element in rhs:\n result.append([candidate]+element)\n\n prev = candidate\n return result","repo_name":"xuychen/Leetcode","sub_path":"1-100/31-40/40-combinationSum2/combinationSum2.py","file_name":"combinationSum2.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42125483010","text":"from rest_framework import serializers\nfrom api.users.serializers import PaperuserSerializer, PaperuserListSerializer\nfrom apps.papers.models import Paper, Question, Choice\n# from api.answers.serializers import ParticipateSerializer\nimport json\n\n\nclass ChoiceSerializer(serializers.ModelSerializer):\n class Meta:\n model = Choice\n fields = \"__all__\"\n\n\nclass QuestionSerializer(serializers.ModelSerializer):\n choices = ChoiceSerializer(many=True, read_only=True)\n\n class Meta:\n model = Question\n fields = (\n 'paper',\n 'content',\n 'type',\n 'choices',\n 'is_multiple'\n )\n\n\nclass BriefQuestionSerializer(serializers.ModelSerializer):\n choices = ChoiceSerializer(many=True, read_only=True)\n\n class Meta:\n model = Question\n fields = (\n 'type',\n 'content',\n 'is_multiple',\n 'choices'\n )\n\n\nclass PaperCreateSerializer(serializers.ModelSerializer):\n # questions = QuestionSerializer(many=True)\n\n class Meta:\n model = Paper\n fields = (\n 'title',\n 'content',\n 'deadline',\n 'preview_image',\n 'poster_url',\n # 'questions',\n )\n\n def to_internal_value(self, data):\n instance = super(PaperCreateSerializer, self).to_internal_value(data)\n if \"questions\" in data:\n questions_str_data = data[\"questions\"]\n questions_json = json.loads(questions_str_data)\n instance[\"questions\"] = questions_json\n return instance\n\n def create(self, validated_data):\n questions_data = validated_data.pop('questions', None)\n paper = Paper.objects.create(**validated_data)\n if questions_data:\n for question_data in questions_data:\n choices_data = question_data.pop('choices', None)\n question = Question.objects.create(paper=paper, **question_data)\n if choices_data:\n for choice_data in choices_data:\n Choice.objects.create(question=question, **choice_data)\n return paper\n\n\nclass PaperSerializer(serializers.ModelSerializer):\n author = PaperuserListSerializer(read_only=True)\n preview_image_thumbnail = serializers.ImageField(read_only=True)\n questions = QuestionSerializer(read_only=True, many=True)\n\n class Meta:\n model = Paper\n fields = (\n 'id',\n 'title',\n 'content',\n 'deadline',\n 'poster_url',\n 'preview_image',\n 'preview_image_thumbnail',\n 'questions',\n 'author',\n )\n read_only_fields = (\n 'created_time',\n 'updated_time',\n )\n\n\nclass PaperListSerializer(serializers.ModelSerializer):\n preview_image_thumbnail = serializers.ImageField(read_only=True)\n\n class Meta:\n model = Paper\n fields = (\n 'id',\n 'title',\n 'deadline',\n 'poster_url',\n 'preview_image_thumbnail',\n )\n read_only_fields = (\n 'created_time',\n 'updated_time',\n )\n","repo_name":"sparcs-kaist/paper-api","sub_path":"paper/api/papers/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"11891020876","text":"def bounded_repeater(value, max_repeats):\n for _ in range(max_repeats):\n yield value\n\nfor i in bounded_repeater(\"Hello\", 5):\n print(i)\n\n\niterator = ('hello' for i in range(3))\nprint(type(iterator))\nfor i in iterator:\n print(i)\nfor i in ('hello' for i in range(3)):\n print(i)\n\n\n# generators chains\ndef integers():\n for i in range(1, 9):\n yield i\n\ndef squared(seq):\n for i in seq:\n yield i * i\n\nchain = squared(integers())\nprint(list(chain))\n","repo_name":"Inframercury/python-tutorials","sub_path":"generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71067846359","text":"import numpy as np\r\n\r\n# create dictionary for stats\r\nCOMUS_FILE=open('COMUSTATS_1','r')\r\nparameters={}\r\nfor line in COMUS_FILE:\r\n line=line.strip().split()\r\n for k in range(0,len(line)):\r\n parameters[k]=[]\r\n\r\nfor x in range(0,290000):\r\n COMUS_FILE=open('COMUSTATS_{}'.format(x),'r')\r\n j=0\r\n COMUS_FILE.readline()\r\n for line in COMUS_FILE:\r\n line=line.strip().split()\r\n for k in range(0,len(line)):\r\n parameters[k].append(float(line[k]))\r\n for y in range(0,len(parameters)):\r\n parameters[y]=[min(parameters[y]),max(parameters[y])]\r\n print(parameters)\r\n\r\nCOMUS_MIN_MAX=open('COMUS_MIN_MAX','w')\r\nfor w in range(0,len(parameters)):\r\n min=str(parameters[w][0])\r\n max=str(parameters[w][1])\r\n COMUS_MIN_MAX.write(min+'\\t'+max+'\\n')\r\n","repo_name":"johnpatramanis/Ambracia_Reworked","sub_path":"comustats_min_max.py","file_name":"comustats_min_max.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"70151984277","text":"def max_diff(lista):\n min_elem = min(lista)\n max_elem = max(lista)\n\n return max_elem - min_elem\n\ndef count_char_occur(sentence):\n occurrences = dict()\n\n for c in sentence:\n occurrences.setdefault(c,0)\n occurrences[c] += 1\n\n return occurrences\n\nif __name__ == \"__main__\":\n r = count_char_occur('Teste de SPLN!!!')\n print(r)","repo_name":"joaoprp111/Resolucao-Testes-SPLN","sub_path":"Teste-2019/1_a.py","file_name":"1_a.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70689234519","text":"from Graph import Graph\n\nclass Test(Graph):\n def __init__(self,v):\n super().__init__(v)\n\n def dfs(self,i,j,tc,n):\n tc[i][j] = True\n # print(\"=>\",i,j)\n if (i+1 < n) and (self.graph[i+1][j] <= self.graph[i][j]) and not tc[i+1][j]:\n # print(\"down\")\n self.dfs(i+1,j,tc,n)\n if (i-1 >= 0) and (self.graph[i-1][j] <= self.graph[i][j]) and not tc[i-1][j]:\n # print(\"up\", self.graph[i-1][j] <= self.graph[i][j])\n self.dfs(i-1,j,tc,n)\n if (j+1 < n) and (self.graph[i][j+1] <= self.graph[i][j]) and not tc[i][j+1]:\n # print(\"right\")\n self.dfs(i,j+1,tc,n)\n if (j-1 >= 0) and (self.graph[i][j-1] <= self.graph[i][j]) and not tc[i][j-1]:\n # print(\"left\")\n self.dfs(i,j-1,tc,n) \n\n def MinTraversal(self):\n t = []\n tc = [[False for i in range(self.length+2)] for i in range(self.length+2)]\n for i in range(self.length):\n for j in range(self.length):\n t.append([self.graph[i][j], i, j])\n \n g = sorted(t, key = lambda x: x[0],reverse=True) #sort the vertex by value\n # print(g)\n n = self.length\n print(\"Initial Vertex to traverse the entire graph\")\n for vertex in g:\n if not tc[vertex[1]][vertex[2]]:\n print(vertex[1], vertex[2])\n self.dfs(vertex[1],vertex[2],tc,n)\n\n\n \n\n\nif __name__ == \"__main__\":\n g = Test(3)\n g.addEdge(0, 0, 1)\n g.addEdge(0, 1, 2) \n g.addEdge(0, 2, 3)\n g.addEdge(1, 0, 2)\n g.addEdge(1, 1, 3) \n g.addEdge(1, 2, 1) \n g.addEdge(2, 0, 1) \n g.addEdge(2, 1, 1) \n g.addEdge(2, 2, 1)\n g.printGraph()\n # g.printEdges()\n g.MinTraversal()\n # g.PathFinder(5,3)","repo_name":"Chan-Dru/g4g","sub_path":"problem/Graph-MinInitialVertexToTraverse.py","file_name":"Graph-MinInitialVertexToTraverse.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7899413102","text":"__author__ = 'Marko Milutinovic'\n\n\"\"\"\nThis class implements a binary data compressor. The base vocabulary for the compressor will be 256 symbols, 0-255 and a termination symbol\nwhose value is 256. An Arithmetic Coding encoder will be used to encode the data into binary.\n\nThis code is designed as a proof of concept and has been designed with simplicity in mind. Efficiency is not a goal in\nthis implementation.\n\nThe compressor will go through five stages in order to compress the data.\n\nThe stages are as follows:\n 1. The Burrows-Wheeler transform will be performed on the data. This stage will maximize the runs of symbols\n 2. Replace runs of symbols with initial symbol and extra symbol indicating length of run. Extended symbols will be\n added to support this.\n 3. Encoded data into binary using an encoder\n\"\"\"\n\nfrom array import *\nfrom AREncoder import AREncoder\nimport utils\n\ndataSorting = None\ndataSortingSize = 0\n\n# This class is used to sort data for the BW transform\nclass SortKey:\n def __init__(self, keyData_, *args):\n self.mIndex = keyData_[0]\n self.mData = keyData_[1]\n self.mDataSize = keyData_[2]\n\n def __lt__(self, rightKey_):\n for i in range(0, self.mDataSize):\n leftData = self.mData[(i+self.mIndex)%self.mDataSize]\n rightData = self.mData[(i+rightKey_.mIndex)%self.mDataSize]\n\n if(leftData < rightData):\n return True\n elif(leftData > rightData):\n return False\n\n return False\n\n def __gt__(self, rightPermutationIndex_):\n return False\n\n def __eq__(self, rightPermutationIndex_):\n return False\n\n def __le__(self, other):\n return False\n\n def __ge__(self, other):\n return False\n\n def __ne__(self, other):\n return False\n\n\nclass Kompressor:\n BASE_BINARY_VOCABULARY_SIZE = 257 # 0-255 for 8-bit characters plus termination symbol\n TERMINATION_SYMBOL = 256 # Used to indicate end of compression sequence\n INVALID_SYMBOL = 0xFFFF\n\n def __init__(self, sectionSize_, genericMaxRun_, encoderWordSize_ = 16):\n \"\"\"\n Constructor\n\n :param sectionSize_: Data section size to use to break up data when compressing\n :param genericMaxRun_: The max run of generic symbols\n :param encoderWordSize_: The size of words (in bits) to use for encoding data\n :return:\n \"\"\"\n\n # Section size must be greater than 0\n if(sectionSize_ < 1):\n raise Exception('Section size must be greater than 0')\n\n # Ensure that generic max run is at least one\n if(genericMaxRun_ < 1):\n genericMaxRun_ = 1\n\n self.mSectionSize = sectionSize_\n self.mGenericMaxRun = genericMaxRun_\n self.mGenericRunLengthStart = self.BASE_BINARY_VOCABULARY_SIZE\n\n self.mVocabularySize = self.BASE_BINARY_VOCABULARY_SIZE + genericMaxRun_\n self.mBWTransformStoreBytes = utils.getMinBytesToRepresent(sectionSize_)\n self.mSectionTransformDataMaxSize = sectionSize_ + self.mBWTransformStoreBytes\n self.mSectionTransformData = array('i', [0]*(self.mSectionTransformDataMaxSize))\n self.mEncoder = AREncoder(encoderWordSize_, self.mVocabularySize)\n\n self.mContinuousModeEnabled = False\n self.mContinuousModeTotalData = 0\n self.mContinuousModeDataCompressed = 0\n\n def _replaceRunsGeneric(self, runLengthSymbolStart_, maxRunLength_, dataSection_, dataSize_):\n \"\"\"\n Replace runs of symbols with generic symbol replacements. A run greater or equal to two symbols should be replaced\n with the first symbol in the run and an extended symbol to indicate how many times it's repeated.\n\n :param runLengthSymbolStart_: First extended symbol that is used to indicate how many times the original symbol is repeated. First symbol indicates a repeat of one\n :param maxRunLength_: The max size of a run that can be replaced\n :param dataSection_: The data section on which we are working. This is an array\n :param dataSize_: The size of the array\n :return: The new size of the dataSection_ array after replacement is finished\n \"\"\"\n maxDuplicateCount = maxRunLength_ - 1\n duplicateCount = 0\n outDataIndex = 0\n\n # Start with invalid symbol\n currentSymbol = self.INVALID_SYMBOL\n\n # If no data just return 0\n if((dataSize_ == 0) or (maxRunLength_ <= 1)):\n return dataSize_\n\n # Go through all the data\n for i in range(0, dataSize_):\n # If the next symbol encountered is a repeat increment the duplicate count, otherwise process change\n if(currentSymbol == dataSection_[i]):\n duplicateCount += 1\n else:\n #If this is not the first symbol encountered process any possible runs\n if(currentSymbol != self.INVALID_SYMBOL):\n\n # Insert the previous symbol\n dataSection_[outDataIndex] = currentSymbol\n outDataIndex += 1\n\n # If the run is greater than the max put in max run symbol.\n while(duplicateCount > maxDuplicateCount):\n dataSection_[outDataIndex] = runLengthSymbolStart_ + maxDuplicateCount - 1\n duplicateCount -= maxDuplicateCount\n outDataIndex += 1\n\n # If the run is greater that or equal to 1, insert the replacement symbol. Run count does not include original symbol\n if(duplicateCount >= 1):\n dataSection_[outDataIndex] = (runLengthSymbolStart_ + duplicateCount - 1)\n outDataIndex += 1\n\n duplicateCount = 0\n currentSymbol = dataSection_[i]\n\n # Handle the last outstanding symbol\n dataSection_[outDataIndex] = currentSymbol\n outDataIndex += 1\n\n #TODO: need test for this case\n # If the run is greater than the max put in max run symbol. Run count includes original symbol\n while(duplicateCount > maxDuplicateCount):\n dataSection_[outDataIndex] = runLengthSymbolStart_ + maxDuplicateCount - 1\n duplicateCount -= maxDuplicateCount\n outDataIndex += 1\n\n # If the run is greater that or equal to 1, insert the replacement symbol\n if(duplicateCount >= 1):\n dataSection_[outDataIndex] = (runLengthSymbolStart_ + duplicateCount - 1)\n outDataIndex += 1\n\n return outDataIndex\n\n def _bytearrayLessThan(self, originalData_, leftPermutationIndex_, rightPermutationIndex_, len_):\n \"\"\"\n Determine which byte array is less based on data sorted in lexigraphical order. Use the permutation indeces and the original\n data to construct byte arrays that are being compared. If left is smaller return -1, if right is smaller return 1\n and if they are the same return 0\n\n :param originalData_: The original byte array\n :param leftData_: Permutation index of left side. This is a permutation index which will be used to construct the byte array from the original data\n :param rightData_: Permutation index of right side. This is a permutation index which will be used to construct the byte array from the original data\n :param len_: Length of left and right byte arrays (NOTE: they must be the same length)\n\n :return: -1 ir leftData < rightdata, 1 if rightData < leftData, 0 if rightData == leftData\n \"\"\"\n for i in range(0, len_):\n leftData = originalData_[(i+leftPermutationIndex_)%len_]\n rightData = originalData_[(i+rightPermutationIndex_)%len_]\n if(leftData < rightData):\n return -1\n elif(leftData > rightData):\n return 1\n\n return 0\n\n def _performBWTransform(self, dataSection_, dataSize_, transformedData_, transformedDataMaxLen_):\n \"\"\" Perform BW transform on dataSection_. This transform will maximize the chances of equal bytes being grouped\n together. The result will be stored in transformedData_\n\n :param dataSection_: The data to be transformed which is an array\n :param dataSize_: The length of the data to be transformed\n :param transformedData_: The transformed data will be stored here. There must be at least inLen_ + self.mBWTransformStoreBytes bytes available. This is an array\n :param transformedDataLen_: The length of outputData_. Must be at least inLen_ + self.mBWTransformStoreBytes bytes\n :return: The size of the transformed data\n \"\"\"\n\n if(transformedDataMaxLen_ < (dataSize_ + self.mBWTransformStoreBytes)):\n raise Exception(\"Output data array to small\")\n\n #K = SortKey(dataSection_, dataSize_)\n sortData = []\n for i in range(0, dataSize_):\n sortData.append([i, dataSection_, dataSize_])\n\n indecesOfDataPermutations = sorted(sortData, key=SortKey)\n\n #Find the original data sequence in the sorted indecesOfDataPermutations\n originalSequenceIndex = indecesOfDataPermutations.index([0, dataSection_, dataSize_])\n\n # Add the original sequence index at the front of the transform (split into bytes, little endian)\n for i in range(0, self.mBWTransformStoreBytes):\n transformedData_[i] = ((originalSequenceIndex >> (i*8)) & 0xFF)\n\n for i in range(self.mBWTransformStoreBytes, dataSize_ + self.mBWTransformStoreBytes):\n transformedData_[i] = dataSection_[(dataSize_ - 1 + indecesOfDataPermutations[i-self.mBWTransformStoreBytes][0])%dataSize_]\n\n return (dataSize_ + self.mBWTransformStoreBytes)\n\n def kompress(self, inputData_, inputDataLen_, outputData_, maxOutputLen_, lastDataBlock=True):\n \"\"\"\n Pass in integer array of data that needs to be compressed. The compressed data will\n be stored in the outputData_ bytearray.\n\n :param inputData_: bytearray that holds the data that needs to be compressed. Data will be modified during compression sequence\n :param inputDataLen_: The data size must be less than or equal to self.mSectionSize\n :param outputData_: Byte array that will hold the compressed binary data\n :param maxOutputLen_: The maximum size of the outputData_ array. If this is not enough to store compressed data an exception will be thrown\n :return: Return the size of the compressed data in outputData_\n \"\"\"\n\n lengthAfterSymbol1Replacement = 0\n lengthAfterSymbol2Replacement = 0\n lengthAfterBWTransform = 0\n lengthAfterGenericReplacement = 0\n\n # If data exceeds section size throw exception\n if(inputDataLen_ > self.mSectionSize):\n raise Exception('Data length exceeds max section size')\n\n # Transform data using BW transform\n lengthAfterBWTransform = self._performBWTransform(inputData_, inputDataLen_, self.mSectionTransformData, self.mSectionTransformDataMaxSize)\n\n # Perform generic symbol run replacement\n lengthAfterGenericReplacement = self._replaceRunsGeneric(self.mGenericRunLengthStart, self.mGenericMaxRun, self.mSectionTransformData, lengthAfterBWTransform)\n\n # Encode the data\n self.mSectionTransformData[lengthAfterGenericReplacement] = self.TERMINATION_SYMBOL\n lengthAfterGenericReplacement += 1\n\n return self.mEncoder.encode(self.mSectionTransformData, lengthAfterGenericReplacement, outputData_, maxOutputLen_, lastDataBlock=lastDataBlock)\n\n def reset(self):\n \"\"\"\n Reset the encoder. This will reset all encoder statistics. Dekompressor must be reset as well otherwise we will not be able to decompress data\n\n :return:\n \"\"\"\n self.mEncoder.reset()","repo_name":"markomilutin/kompressor","sub_path":"Kompressor.py","file_name":"Kompressor.py","file_ext":"py","file_size_in_byte":11837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"40094621686","text":"\"\"\"Circular Vector Diagram (CVD). Main window.\"\"\"\n# 1. std\nimport cmath\n# 2. 3rd\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import QDialog, QAction, QVBoxLayout, QToolBar, QSplitter, QWidget, QSizePolicy\n# 3. local\nfrom iosc.sig.tools.cvdtable import CVDTable\nfrom iosc.sig.tools.cvdwidget import CVDiagramView\nfrom iosc.sig.tools.ptrswitcher import PtrSwitcher\nfrom iosc.sig.widget.sigsuit import AnalogSignalSuit\nfrom iosc.sig.tools.cvddialog import SelectCVDSignalsDialog\n\n\nclass CVDWindow(QDialog):\n \"\"\"Main CVD window.\"\"\"\n\n __ptr_uid: int\n __i: int\n __ass_list: list[AnalogSignalSuit] # just shortcut\n ss_used: list[AnalogSignalSuit]\n ss_base: AnalogSignalSuit\n toolbar: QToolBar\n chart: CVDiagramView\n table: CVDTable\n action_settings: QAction\n action_ptr: PtrSwitcher\n action_close: QAction\n\n def __init__(self, parent: 'ComtradeWidget'): # noqa: F821\n \"\"\"Init CVDWindow object.\"\"\"\n super().__init__(parent)\n self.__ptr_uid = 0 # MainPtr\n self.__i = parent.main_ptr_i\n self.__ass_list = parent.ass_list\n self.ss_used = list()\n self.ss_base = parent.ass_list[0]\n self.__mk_widgets()\n self.__mk_layout()\n self.__mk_actions()\n self.__mk_toolbar()\n self.setWindowTitle(self.tr(\"Vector Diagram\"))\n self.setWindowModality(Qt.WindowModality.NonModal)\n # self.setWindowFlag(Qt.Dialog)\n parent.signal_ptr_moved_main.connect(self.__slot_ptr_moved_main)\n parent.signal_ptr_moved_tmp.connect(self.__slot_ptr_moved_tmp)\n self.finished.connect(self.__slot_post_close)\n\n @property\n def t_i(self):\n \"\"\":return: Current MainPtr.i.\"\"\"\n return self.__i\n\n def get_base_angle(self) -> float:\n \"\"\":return: Base angle (of base signal).\"\"\"\n return cmath.phase(self.ss_base.hrm(1, self.t_i))\n\n def __mk_widgets(self):\n self.toolbar = QToolBar(self)\n self.chart = CVDiagramView(self)\n self.table = CVDTable(self)\n\n def __mk_layout(self):\n \"\"\"Lay out child widgets.\n\n They are:\n - toolbar\n - plot\n - table\n \"\"\"\n splitter = QSplitter(Qt.Vertical, self)\n splitter.setStyleSheet(\"QSplitter::handle{background: grey;}\")\n splitter.addWidget(self.chart)\n splitter.addWidget(self.table)\n self.setLayout(QVBoxLayout())\n self.layout().setContentsMargins(0, 0, 0, 0)\n self.layout().setSpacing(0)\n self.layout().addWidget(self.toolbar)\n self.layout().addWidget(splitter)\n\n def __mk_actions(self):\n # noinspection PyArgumentList\n self.action_settings = QAction(QIcon.fromTheme(\"document-properties\"),\n self.tr(\"&Select signals\"),\n self,\n shortcut=\"Ctrl+S\",\n triggered=self.__do_settings)\n # noinspection PyArgumentList\n self.action_close = QAction(QIcon.fromTheme(\"window-close\"),\n self.tr(\"&Close\"),\n self,\n shortcut=\"Ctrl+V\",\n triggered=self.close)\n self.action_ptr = PtrSwitcher(self)\n\n def __mk_toolbar(self):\n spacer = QWidget(self)\n spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)\n spacer.setVisible(True)\n self.toolbar.addAction(self.action_settings)\n self.toolbar.addWidget(self.action_ptr.tb)\n self.toolbar.addWidget(spacer)\n self.toolbar.addAction(self.action_close)\n\n def __do_settings(self):\n ss_used_i = set([ss.i for ss in self.ss_used]) # WARN: works if ss.signal.i <=> self.__ass_list[i]\n ss_base_i = self.ss_base.i\n retvalue = SelectCVDSignalsDialog(self.__ass_list, ss_used_i, ss_base_i).execute()\n if retvalue is not None:\n self.ss_used.clear()\n self.ss_used = [self.__ass_list[i] for i in retvalue[0]]\n self.ss_base = self.__ass_list[retvalue[1]]\n self.chart.reload_signals()\n self.table.reload_signals()\n\n def __slot_ptr_moved(self, i: int):\n self.__i = i\n self.chart.refresh_signals()\n self.table.refresh_signals()\n\n def __slot_ptr_moved_main(self, i: int):\n if self.__ptr_uid == 0:\n self.__slot_ptr_moved(i) # Plan B: get from parent\n\n def __slot_ptr_moved_tmp(self, uid: int, i: int):\n if self.__ptr_uid == uid:\n self.__slot_ptr_moved(i) # Plan B: get from parent\n\n def slot_ptr_switch(self, uid: int):\n \"\"\"Switch between pointers.\"\"\"\n if uid != self.__ptr_uid: # skip if not changed\n self.__ptr_uid = uid\n self.__slot_ptr_moved(self.parent().tmp_ptr_i[uid] if uid else self.parent().main_ptr_i)\n\n def __slot_post_close(self):\n self.parent().action_vector_diagram.setEnabled(True)\n","repo_name":"tieugene/iosc.py","sub_path":"iosc/sig/tools/cvdwindow.py","file_name":"cvdwindow.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"24633486229","text":"import random\nlist=['rock','paper','scissor']\nuser= input('select one of these rock,paper,scissor? : ')\nif user in list:\n\tlist.remove(user)\n\tcmp=random.choice(list)\n\tprint ('Computer Choice :',cmp)\n\tif user=='rock' and cmp== 'paper':\n\t\tprint('Paper Win')\n\telif user=='rock' and cmp=='scissor':\n\t\tprint('Rock Win')\n\telif user=='paper' and cmp=='scissor':\n\t\tprint('Scissor win')\nelse:\n\tprint('You selected Wrong item try agian')","repo_name":"Santhosh071993/Python-Code","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19868226468","text":"import os\nfrom collectFeatures import logFeatures, buildFeaturesJudgmentsFile\nfrom loadFeatures import initDefaultStore, loadFeatures\n\n\ndef trainModel(judgmentsWithFeaturesFile, modelOutput, whichModel=6):\n # java -jar RankLib-2.6.jar -ranker 6 -train sample_judgments_wfeatures.txt -save model.txt\n cmd = \"java -jar RankLib-2.8.jar -ranker %s -train %s -save %s -frate 1.0\" % (whichModel, judgmentsWithFeaturesFile, modelOutput)\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n print(\"Running %s\" % cmd)\n os.system(cmd)\n pass\n\n\ndef saveModel(esHost, scriptName, featureSet, modelFname):\n \"\"\" Save the ranklib model in Elasticsearch \"\"\"\n import requests\n import json\n from urllib.parse import urljoin\n modelPayload = {\n \"model\": {\n \"name\": scriptName,\n \"model\": {\n \"type\": \"model/ranklib\",\n \"definition\": {\n }\n }\n }\n }\n\n with open(modelFname) as modelFile:\n modelContent = modelFile.read()\n path = \"_ltr/test_featurestore/_featureset/%s/_createmodel\" % featureSet\n fullPath = urljoin(esHost, path)\n modelPayload['model']['model']['definition'] = modelContent\n print(\"POST %s\" % fullPath)\n resp = requests.post(fullPath, json.dumps(modelPayload))\n print(resp.status_code)\n if (resp.status_code >= 300):\n print(resp.text)\n\n\n\n\n\nif __name__ == \"__main__\":\n import configparser\n from elasticsearch import Elasticsearch\n from judgments import judgmentsFromFile, judgmentsByQid\n\n config = configparser.ConfigParser()\n config.read('settings.cfg')\n esUrl = config['DEFAULT']['ESHost']\n\n es = Elasticsearch(esUrl, timeout=1000)\n # Load features into Elasticsearch\n initDefaultStore(esUrl)\n loadFeatures(esUrl)\n # Parse a judgments\n movieJudgments = judgmentsByQid(judgmentsFromFile(filename='sample_judgments.txt'))\n # Use proposed Elasticsearch queries (1.json.jinja ... N.json.jinja) to generate a training set\n # output as \"sample_judgments_wfeatures.txt\"\n logFeatures(es, judgmentsByQid=movieJudgments)\n buildFeaturesJudgmentsFile(movieJudgments, filename='sample_judgments_wfeatures.txt')\n # Train each ranklib model type\n for modelType in [0,1,2,3,4,5,6,7,8,9]:\n # 0, MART\n # 1, RankNet\n # 2, RankBoost\n # 3, AdaRank\n # 4, coord Ascent\n # 6, LambdaMART\n # 7, ListNET\n # 8, Random Forests\n # 9, Linear Regression\n print(\"*** Training %s \" % modelType)\n trainModel(judgmentsWithFeaturesFile='sample_judgments_wfeatures.txt', modelOutput='model.txt', whichModel=modelType)\n saveModel(esHost=esUrl, scriptName=\"test_%s\" % modelType, featureSet='movie_features', modelFname='model.txt')\n","repo_name":"sully90/dp-elasticutils-ltr","sub_path":"src/test/resources/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70375862998","text":"def fib_tab(n):\n # 코드를 작성하세요.\n fib_table = [0, 1, 1]\n\n for i in range(3, n + 1):\n fib_table.append(fib_table[i - 1] + fib_table[i - 2])\n\n return fib_table[n]\n\ndef fib_tab_mytry(n):\n # 코드를 작성하세요.\n if n < 3:\n return n\n\n cache = {1: 1, 2: 1}\n\n for i in range(1, n-1):\n cache[i+2] = cache[i] + cache[i+1]\n\n return cache[n]\n\n\n# 테스트\nprint(fib_tab(10))\nprint(fib_tab(56))\nprint(fib_tab(132))\n","repo_name":"cjy13753/study_dsal","sub_path":"dynamicpro/DynamicProgramming_07_TabulationFib.py","file_name":"DynamicProgramming_07_TabulationFib.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28630594806","text":"from pymatgen.io.qchem.outputs import QCOutput\nimport glob, csv\n\nnum_outputs= len(glob.glob(\"eda*.out\"))\n\nenergy = [None]*num_outputs\nprp = [None]*num_outputs\nfrz = [None]*num_outputs\npol = [None]*num_outputs\nvct = [None]*num_outputs\ninter = [None]*num_outputs\n\nelec = [None]*num_outputs\npauli = [None]*num_outputs\ndisp = [None]*num_outputs\n\nfor file in glob.glob(\"eda*.out\"):\n output = QCOutput(filename = file)\n i_string= file.split('.')[0][3:len(file)]\n i = int(i_string)\n energy[i-1] = output.data['final_energy']\n\nfor file in glob.glob(\"eda*.out\"):\n output = QCOutput(filename = file)\n i_string= file.split('.')[0][3:len(file)]\n i = int(i_string)\n\n prp[i-1] = output.data['EDA_data']['E_prp']\n frz[i-1] = output.data['EDA_data']['E_frz']\n pol[i-1] = output.data['EDA_data']['E_pol']\n vct[i-1] = output.data['EDA_data']['E_vct']\n inter[i-1] = output.data['EDA_data']['E_int']\n\n elec[i-1] = output.data['EDA_data']['E_elec']\n pauli[i-1] = output.data['EDA_data']['E_pauli']\n disp[i-1] = output.data['EDA_data']['E_disp']\n\nwith open('EDA_data.csv', mode='w') as csv_file:\n fieldnames = ['Filename','Energy','E_prp','E_frz','E_pol','E_vct','E_int','E_elec','E_pauli','E_disp']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames,delimiter=',')\n writer.writeheader()\n for n in range(num_outputs):\n writer.writerow(\n {\n 'Filename':'eda'+str(n+1)+'.out',\n 'E_Energy':energy[n],\n 'E_prp':prp[n],\n 'E_frz':frz[n],\n 'E_pol':pol[n],\n 'E_vct':vct[n],\n 'E_int':inter[n],\n\n 'E_elec':elec[n],\n 'E_pauli':pauli[n],\n 'E_disp':disp[n]\n }\n )\n","repo_name":"stephen-quiton/stephen-quiton.github.io","sub_path":"tutorial_docs/eda_firework_example/extract_data.py","file_name":"extract_data.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"24458932048","text":"import unittest\nimport pickle\nimport os, sys\nimport csv\nimport random\nimport compress_pickle\nimport itertools\nimport numpy as np\nfrom collections import defaultdict\nfrom gurobipy import read\nfrom unittest.mock import patch\n\nfrom pybkb.learn.backends.bkb.gobnilp import BKBGobnilpBackend\nfrom pybkb.utils.probability import build_feature_state_map\nfrom pybkb.scores import MdlEntScoreNode\n\nclass BKBGobnilpBackendTestCase(unittest.TestCase):\n def setUp(self):\n # Load dataset\n self.basepath = os.path.dirname(os.path.abspath(__file__))\n with open(os.path.join(self.basepath, '../../../', 'data/iris-standard_classification-no_missing_values.dat'), 'rb') as f_:\n self.data, self.feature_states, self.srcs = compress_pickle.load(f_, compression='lz4')\n self.feature_states_map = build_feature_state_map(self.feature_states)\n self.feature_states_index_map = {fs: idx for idx, fs in enumerate(self.feature_states)}\n self.node_encoding_len = len(self.feature_states)\n self.data_eff = BKBGobnilpBackend.format_data_for_probs(self.data)\n\n def test_regress_learn_endstage_scores(self):\n # We are using Iris so we can do all parent sets.\n backend = BKBGobnilpBackend(\n score='mdl_ent',\n palim=None,\n only='data',\n )\n # Gather scores from backend\n scores, all_scores, store = backend.learn(\n self.data,\n self.feature_states,\n self.srcs,\n end_stage='scores',\n )\n\n # Test 1: Ensure we get a score for each source.\n self.assertEqual(len(scores), len(self.srcs))\n\n # Test 2: Ensure we look at the correct number of parents based on palim.\n max_pasets = defaultdict(set)\n for (x, pa_set), score in all_scores.items():\n max_pasets[x].add(len(pa_set))\n self.assertListEqual(\n [max(values) for _, values in max_pasets.items()],\n [len(self.feature_states_map)-1 for _ in range(len(self.feature_states))]\n )\n\n # Test 3: Run scores independently and compare to regression test to backend\n store1 = None\n for x_state_idx, (feature, state) in enumerate(self.feature_states):\n for palim in range(len(self.feature_states_map)):\n for pa_features in itertools.combinations(set(self.feature_states_map.keys()) - {feature}, r=palim):\n for pa_prod in itertools.product(*[self.feature_states_map[pa] for pa in pa_features]):\n score_node = MdlEntScoreNode(\n x_state_idx,\n self.node_encoding_len,\n rv_level=False,\n pa_set=list(pa_prod),\n states=None,\n indices=True,\n )\n h1, store1 = score_node._calc_instantiated_score(self.data, self.feature_states_index_map, store1, self.data_eff)\n if (x_state_idx, frozenset(list(pa_prod))) not in all_scores:\n self.assertEqual(h1, 0)\n else:\n self.assertAlmostEqual(-h1, all_scores[(x_state_idx, frozenset(list(pa_prod)))])\n \n # Test 4: Compare to regression scores for the iris dataset\n backend = BKBGobnilpBackend(\n score='mdl_ent',\n palim=None,\n only=None,\n )\n scores, all_scores, store = backend.learn(\n self.data,\n self.feature_states,\n self.srcs,\n end_stage='scores',\n )\n with open(os.path.join(self.basepath, 'regression_files/iris-bkb-gobnilp-mdlent-regression-scores.csv'), 'r') as f_:\n reader = csv.reader(f_)\n for i, row in enumerate(reader):\n # Remove header row\n if i == 0:\n continue\n data_idx = int(row[0])\n x_state_idx = int(row[1])\n score = float(row[2])\n pa_set = frozenset([int(r) for r in row[3:]])\n # Check that all scores is consistent\n self.assertAlmostEqual(score, all_scores[(x_state_idx, pa_set)])\n # Check that source scores are consistent (scores are in str's for Gobnilp so need to cast back)\n self.assertAlmostEqual(score, scores[data_idx][str(x_state_idx)][frozenset([str(pa) for pa in pa_set])])\n # Uncomment to write file\n '''\n filepath = os.path.join(self.basepath, 'regression_files/iris-bkb-gobnilp-mdlent-regression-scores.csv')\n for i, (data_idx, _scores) in enumerate(scores.items()):\n if i == 0:\n BKBGobnilpBackend.write_scores_to_file(_scores, data_idx, filepath, open_mode='w')\n continue\n BKBGobnilpBackend.write_scores_to_file(_scores, data_idx, filepath, open_mode='a', write_header=False)\n '''\n\n def test_regress_learn_no_mp(self):\n # We are using Iris so we can do all parent sets.\n backend = BKBGobnilpBackend(\n score='mdl_ent',\n palim=None,\n only=None,\n )\n # Gather scores from backend\n bkfs, report = backend.learn(\n self.data,\n self.feature_states,\n self.srcs,\n end_stage=None,\n nsols=1,\n kbest=True,\n )\n # Test 1: Regression test to Gurobi MIP model\n # Gurobi has nondeterministic behaviour so can not use bkfs directly for regression tests.\n # But we can use the base Gurobi MIP model that is used to solve to ensure the correct problem is built everytime.\n _stdout = sys.stdout\n f = open(os.devnull, 'w')\n sys.stdout = f\n for i, m in enumerate(backend.models):\n # We have to write the model first so that when we load it back in the Fingerprint is the same. Weird. \n m.write('/tmp/iris-model.mps')\n m_regress = read(os.path.join(self.basepath, f'regression_files/model-iris-{i}.mps'))\n m_loaded = read('/tmp/iris-model.mps')\n self.assertEqual(m_loaded.Fingerprint, m_regress.Fingerprint)\n sys.stdout = _stdout\n f.close()\n \n def test_regress_learn_with_mp(self):\n # We are using Iris so we can do all parent sets.\n backend = BKBGobnilpBackend(\n score='mdl_ent',\n palim=None,\n only=None,\n )\n # Gather scores from backend\n bkfs, report = backend.learn(\n self.data,\n self.feature_states,\n self.srcs,\n end_stage=None,\n nsols=1,\n kbest=True,\n num_workers=10,\n )\n # Test 1: Regression test to Gurobi MIP model\n # Gurobi has nondeterministic behaviour so can not use bkfs directly for regression tests.\n # But we can use the base Gurobi MIP model that is used to solve to ensure the correct problem is built everytime.\n _stdout = sys.stdout\n f = open(os.devnull, 'w')\n sys.stdout = f\n for i, m in enumerate(backend.models):\n # We have to write the model first so that when we load it back in the Fingerprint is the same. Weird. \n # Uncomment to write new model\n #m.write(os.path.join(self.basepath, f'regression_files/model-iris-{i}.mps'))\n m.write('/tmp/iris-model.mps')\n m_regress = read(os.path.join(self.basepath, f'regression_files/model-iris-{i}.mps'))\n m_loaded = read('/tmp/iris-model.mps')\n self.assertEqual(m_loaded.Fingerprint, m_regress.Fingerprint)\n sys.stdout = _stdout\n f.close()\n\n def test_regress_learn_beginstage_scores(self):\n # Load in scores\n scores = BKBGobnilpBackend.read_scores_file(\n os.path.join(self.basepath, 'regression_files/iris-bkb-gobnilp-mdlent-regression-scores.csv')\n )\n # We are using Iris so we can do all parent sets.\n backend = BKBGobnilpBackend(\n score='mdl_ent',\n palim=None,\n only=None,\n )\n # Gather scores from backend\n bkfs, report = backend.learn(\n self.data,\n self.feature_states,\n self.srcs,\n begin_stage='scores',\n end_stage=None,\n nsols=1,\n kbest=True,\n num_workers=10,\n scores=scores,\n )\n # Test 1: Regression test to Gurobi MIP model\n # Gurobi has nondeterministic behaviour so can not use bkfs directly for regression tests.\n # But we can use the base Gurobi MIP model that is used to solve to ensure the correct problem is built everytime.\n _stdout = sys.stdout\n f = open(os.devnull, 'w')\n sys.stdout = f\n for i, m in enumerate(backend.models):\n # We have to write the model first so that when we load it back in the Fingerprint is the same. Weird. \n m.write('/tmp/iris-model.mps')\n m_regress = read(os.path.join(self.basepath, f'regression_files/model-iris-{i}.mps'))\n m_loaded = read('/tmp/iris-model.mps')\n self.assertEqual(m_loaded.Fingerprint, m_regress.Fingerprint)\n sys.stdout = _stdout\n f.close()\n","repo_name":"di2ag/pybkb","sub_path":"tests/test_learn/test_backends/test_bkb_gobnilp.py","file_name":"test_bkb_gobnilp.py","file_ext":"py","file_size_in_byte":9682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17218388340","text":"salida = False\nagenda = dict()\n\nwhile not salida:\n accion = input(\"¿Que quieres hacer ? [añadir numero[A] / [consultar numero[C] / [salir[S]: \")\n\n if accion == \"A\":\n print(\"vamos a añadir un numero de telefono: \")\n print(\"--------------------------------------\")\n nombre =input(\"Nombre:\")\n numero = input(\"Numero:\")\n agenda[nombre]= numero\n elif accion == \"C\":\n print(\"consultar numero:\")\n print(\"--------------------------------------\")\n nombre = input(\"de quien quieres el numero:\")\n print(agenda[nombre])\n\n\n\n elif accion == \"S\":\n salida =True","repo_name":"Steinspass/mi_primer_programa","sub_path":"agenda_telefonica2.py","file_name":"agenda_telefonica2.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41879791767","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nfrom sklearn.ensemble import RandomForestClassifier\n\nattributes = ['Runtime', 'Aspect_Ratio', 'Content_Rating_Score', 'Genre_Musical', 'Genre_Romance', 'Genre_Sport', 'Genre_Crime', 'Genre_Documentary', 'Genre_Film-Noir', 'Genre_Short', 'Genre_Fantasy', 'Genre_Horror', 'Genre_Comedy', 'Genre_Western', 'Genre_Thriller', 'Genre_War', 'Genre_Animation', 'Genre_Family', 'Genre_Mystery', 'Genre_Adventure', 'Genre_Drama', 'Genre_History', 'Genre_Biography', 'Genre_Sci-Fi', 'Genre_News', 'Genre_Action', 'Release_Month', 'Director_Avg_Movie_Revenue', 'Lead_Actor_Avg_Movie_Revenue', 'Budget', 'Lead_Actor_Name', 'Director_Name', 'Revenue', 'class']\n\ndf = pd.read_csv('real.csv')\nprint(df.head())\n\nX = np.array(df.iloc[:,0:30])\ny = np.array(df['class'])\n\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size=1/5,random_state=0)\n\n\n\nk_value = np.arange(1,80,2)\n# k_value = list(range(1,100, 2))\nk_acc_score =[ ]\n\nprint(k_value)\nfor k in k_value:\n clf=RandomForestClassifier(n_estimators=k+20, random_state=42,n_jobs=-1)\n clf.fit(X_train,y_train)\n y_pred=clf.predict(X_test)\n k_acc_score.append(accuracy_score(y_test,y_pred))\n\nprint(type(k_value))\n# print(k_acc_score)\nplt.plot(k_value, k_acc_score)\nplt.xlabel(\"No. of trees\")\nplt.ylabel(\"Accuracy\")\nplt.scatter(k_value, k_acc_score)\nplt.grid()\nplt.show()\n\n\n\n\n\n# clf=RandomForestClassifier(n_estimators=20, random_state=42,n_jobs=-1)\n\n# clf.fit(X_train,y_train)\n\n# y_pred=clf.predict(X_test)\n\n\n\n\n# print(\"accuracy : {}\".format(accuracy_score(y_test,y_pred)))\n\n\n\n\n","repo_name":"Akhilesh2008/Movie-Prediction-System","sub_path":"Movie-Success-Prediction-main/Algorithms/rain2.py","file_name":"rain2.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2274580139","text":"import vtk\nfrom libcore.mesh import Mesh\nfrom libcore.mixins import ViewportMixin\nfrom libcore.widget import CubeSelector\n\nclass App(ViewportMixin):\n\n def __init__(self):\n super().__init__()\n\n self.style = vtk.vtkInteractorStyleTrackballCamera()\n self.mesh = Mesh('../data/rooster.midres.stl')\n\n self.cube_selector = CubeSelector(self.interactor, self.mesh)\n self.cube_selector.show()\n self.register_callback(vtk.vtkCommand.CharEvent, self.event)\n\n def event(self, caller, ev):\n key = self.interactor.GetKeySym()\n if key == '1':\n self.mesh.clip_by_mesh(self.cube_selector.as_polydata(), True, inplace=True)\n elif key == '2':\n self.mesh.clip_by_mesh(self.cube_selector.as_polydata(), False, inplace=True)\n\n self.rwindow.Render()\n\napp = App()\napp.run()\n","repo_name":"TheFaded69/MyPortfolio","sub_path":"CADSystem/libcore/example/old/cube_select.py","file_name":"cube_select.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4647090193","text":"from Mits.Families.BaseFamily import BaseFamilySerial, BaseFamilyUSB\n\n\nfrom Mits.Chains.ChainBcmUploadMode import ChainBcmUploadMode\nfrom BcmUploadModeConsts import MODELS\nimport serial\n\n\nclass FamilyBcmSerial(BaseFamilySerial): \n def __init__(self, port = None):\n BaseFamilySerial.__init__(self, \"Broadcomm Serial\", ChainBcmUploadMode, port, baud = 115200, parity = serial.PARITY_NONE)\n\n\nclass FamilyBcmUploadMode(BaseFamilyUSB):\n def __init__(self, phone_model):\n\n\n vid = [0x04e8]\n pid = [0x684E, 0x685d, 0x6795]\n\n\n # Models start with GT-S5xxx or GT-S7xxx, the write_endpoint is 2\n if (phone_model is MODELS.S7XXX) or (phone_model is MODELS.S5XXX):\n custom_write_endpoint = 2\n # Models start with GT-S8xxx, the write_endpoint is 3\n elif (phone_model is MODELS.S8XXX):\n custom_write_endpoint = 3\n else:\n raise Exception(\"Trying to create family for unknown model!\")\n BaseFamilyUSB.__init__(self, \"Broadcomm USB Upload Mode\", ChainBcmUploadMode, vid, pid, configuration=1, interface=1, write_endpoint=custom_write_endpoint, read_endpoint=2)\n","repo_name":"TamirAl/cellebrite","sub_path":"python/Mits/Families/Samsung/BcmUploadMode.py","file_name":"BcmUploadMode.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"73535102039","text":"import torchvision.transforms as T\r\nimport torch\r\nimport cv2 as cv\r\nfrom .RealESRGAN import RealESRGAN\r\nfrom PIL import Image\r\nfrom .init import init_supres\r\n\r\ndevice = torch.device('cpu')\r\n\r\ndef preprocessing_std(img_path):\r\n preprocess=T.Compose([\r\n T.Resize(224),\r\n T.CenterCrop(size=224),\r\n T.ToTensor(),\r\n T.Normalize([0.485, 0.456, 0.406],\r\n [0.229, 0.224, 0.225])\r\n ])\r\n return preprocess(img_path)\r\n\r\ndef grayscaling(img_path):\r\n img = cv.bitwise_not(img_path)\r\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\n img = cv.cvtColor(gray, cv.COLOR_GRAY2RGB)\r\n\r\n return img\r\n","repo_name":"Cizz22/final-project","sub_path":"src/utils/search_with_image/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"6415399280","text":"import zmq\nimport rospy\nfrom std_msgs.msg import String\nimport struct\n\ncontext = zmq.Context()\npoller = zmq.Poller()\n\n# 订阅者套接字\nsub_socket = context.socket(zmq.SUB)\nsub_socket.connect(f\"tcp://localhost:5555\")\nsub_socket.setsockopt_string(zmq.SUBSCRIBE, '')\npoller.register(sub_socket, zmq.POLLIN)\n\n# 发布者套接字\npub_socket = context.socket(zmq.PUB)\npub_socket.bind(\"tcp://*:5559\")\n\ndef callback(data):\n pub_socket.send_string(data.data)\n\n# ROS订阅者和发布者\nros_sub = rospy.Subscriber(\"ros_topicc\", String, callback)\nros_pub = rospy.Publisher(\"ros_topic\", String, queue_size=10)\n\n\ndef main_loop():\n while not rospy.is_shutdown():\n try:\n socks = dict(poller.poll())\n except KeyboardInterrupt:\n break\n\n # 监听订阅者\n if sub_socket in socks and socks[sub_socket] == zmq.POLLIN:\n message = sub_socket.recv()\n rospy.loginfo(f\"Received message: {message}\")\n data = struct.unpack('i', message)\n ros_pub.publish(str(data[0]))\n\n context.term()\n\nif __name__ == '__main__':\n rospy.init_node('zmq_ros_node')\n main_loop()","repo_name":"xirhxq/zmq_ros_bridge","sub_path":"ZmqRosBridgeV1.py","file_name":"ZmqRosBridgeV1.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33956057751","text":"import matplotlib.pyplot as plt\n\n# Sample data\nx = [1, 2, 3, 4, 5]\ny = [10, 20, 15, 25, 30]\n\n# Create a line plot\nplt.plot(x, y)\n\n# Set labels and title\nplt.xlabel('X-axis')\nplt.ylabel('Y-axis')\nplt.title('Line Plot')\n\n# Show the plot\nplt.show()","repo_name":"dronify/AER850-Fall23","sub_path":"howtomatplotlib.py","file_name":"howtomatplotlib.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"85"} +{"seq_id":"70870779479","text":"\"\"\"\nProvides data structures for decoding process.\nAuthors:\nHai Dong Luong (573780) \nDesmond Putra (555802) \nAndrew Vadnal (326558) \n\"\"\"\n\nimport bisect\n\n# custom modules\nfrom utils import get_consecutive_parts, get_untranslated_words\n\n\nclass Hypothesis:\n \"\"\"Data structure representing a hypothesis as described in Koehn 06.\"\"\"\n def __init__(self, hyp, trans_opt, input_sent=None, fc_table=None):\n \"\"\"Create a hypothesis expanding on another hypothesis by a\n translation option.\n\n hyp: a hypothesis to be expanded. If None, create an empty hypothesis.\n\n trans_opt: a TranslationOption. Ignored if hyp is None.\n\n input_sent: the input sentence. Only needed when create an empty\n hypothesis. New hypothesis's input sentence is set to expanded\n hypothesis's.\n\n fc_table: future cost table. Only needed when create an empty\n hypothesis. New hypothesis's future cost table is set to expanded\n hypothesis's.\n \"\"\"\n if hyp is not None:\n #hyp.next.append(self)\n self.input_sent = hyp.input_sent\n self.fc_table = hyp.fc_table\n self.trans = {}\n self.trans['input'] = hyp.trans['input'] + [(\n trans_opt.i_start, trans_opt.i_end, trans_opt.input_phrase)]\n self.trans['output'] = (hyp.trans['output'] + \\\n [trans_opt.output_phrase])\n self.trans['score'] = hyp.trans['score'] + trans_opt.score\n else: # create an empty hypothesis\n self.trans = {\n 'input': [],\n 'output': [],\n 'score': 0.0,\n }\n self.input_sent = input_sent\n self.fc_table = fc_table\n\n self.future_cost = 0.0\n parts = get_consecutive_parts(get_untranslated_words(self))\n if parts[0]:\n for part in parts:\n self.future_cost += self.fc_table[part[0][0]][part[-1][0] + 1]\n\n def input_len(self):\n \"\"\"Return the length of input consumed by this hypothesis.\n\n >>> from collections import defaultdict\n >>> from TranslationOption import TranslationOption\n >>> fc_table = defaultdict(lambda: defaultdict(float))\n >>> empty_hypothesis = Hypothesis(\n ... None, None, 'a b c'.split(), fc_table)\n >>> trans_opt = TranslationOption(1, 2, ['b', 'c'], '2', 0.0)\n >>> hypothesis = Hypothesis(empty_hypothesis, trans_opt)\n >>> empty_hypothesis.input_len()\n 0\n >>> hypothesis.input_len()\n 2\n \"\"\"\n l = 0\n for i in self.trans['input']:\n l += len(i[2])\n return l\n\n def identical(self, other):\n \"\"\"Check whether this hypothesis is identical with another one.\n\n Two hypotheses are identical when:\n - They consume the same sequence of input. Ordering doesn't matter,\n with the exception of the last word, i.e:\n 0, 2, 3, 1 == 2, 3, 0, 1;\n This ensures they have the same set of possible expansions.\n - The last input words' positions are identical, ensuring the same\n reordering cost upon hypothesis expansion.\n - The last output words are identical, ensuring that language model\n scores are identical upon expansion.\n \"\"\"\n this_i_sequence, other_i_sequence = [], []\n for phrase in self.trans['input']:\n this_i_sequence += range(phrase[0], phrase[1] + 1)\n for phrase in other.trans['input']:\n other_i_sequence += range(phrase[0], phrase[1] + 1)\n this_i_sequence.sort()\n other_i_sequence.sort()\n\n return this_i_sequence == other_i_sequence and \\\n self.trans['input'][-1][1] == other.trans['input'][-1][1] and \\\n self.trans['output'][-1].split()[-1] == \\\n other.trans['output'][-1].split()[-1]\n\n def __lt__(self, other):\n \"\"\"a.__lt__(b) <==> a < b\n A hypothesis is \"less than\" another hypothesis when the sum of its\n current score and future cost is less than the other one. Used for\n sorting hypothesis.\n \"\"\"\n return self.trans['score'] + self.future_cost < \\\n other.trans['score'] + other.future_cost\n\n def __le__(self, other):\n \"\"\"a.__le__(b) <==> a <= b.\n\n See __lt__(self, other).\n \"\"\"\n return self.trans['score'] + self.future_cost <= \\\n other.trans['score'] + other.future_cost\n\n def __gt__(self, other):\n \"\"\"a.__gt__(b) <==> a > b.\n\n See __lt__(self, other).\n \"\"\"\n return not (self <= other)\n\n def __ge__(self, other):\n \"\"\"a.__ge__(b) <==> a >= b.\n\n See __lt__(self, other).\n \"\"\"\n return not (self < other)\n\n def __str__(self):\n return str(self.trans)\n\n def __repr__(self):\n return str(self.__dict__)\n\n\nclass Stack:\n \"\"\"Data structure representing stacks as described in Koehn 06.\"\"\"\n def __init__(self, size, pruning_type=\"Histogram\", alpha=None):\n \"\"\"Create a stack of specified size.\"\"\"\n self.size = size\n self.hyps = [] # list of hypotheses in ascending order\n self.alpha = alpha\n self.pruning_type = pruning_type\n\n def add(self, hyp):\n \"\"\"Add a hypothesis into the stack.\n\n A hypothesis is added when there is no identical hypothesis or there is\n a worse hypothesis in the stack. Stack gets pruned (histogram) when\n it's over-sized.\n\n Return True when hypothesis is add, False otherwise.\n\n >>> from collections import defaultdict\n >>> from TranslationOption import TranslationOption\n >>> fc_table = defaultdict(lambda: defaultdict(float))\n >>> empty_hypothesis = Hypothesis(\n ... None, None, 'a b c'.split(), fc_table)\n >>> trans_opt = TranslationOption(1, 2, ['b', 'c'], '2', 0.0)\n >>> hypothesis = Hypothesis(empty_hypothesis, trans_opt)\n >>> stack = Stack(10)\n >>> stack.add(hypothesis)\n True\n\n >>> trans_opt = TranslationOption(1, 2, ['b', 'c'], '0 3', -1.0)\n >>> hypothesis = Hypothesis(empty_hypothesis, trans_opt)\n >>> stack.add(hypothesis)\n True\n\n >>> trans_opt = TranslationOption(1, 2, ['b', 'c'], '1 3', -2.0)\n >>> hypothesis = Hypothesis(empty_hypothesis, trans_opt)\n >>> # Not added because identical but worse score\n >>> stack.add(hypothesis)\n False\n\n >>> trans_opt = TranslationOption(1, 2, ['b', 'c'], '2 3', -0.5)\n >>> hypothesis = Hypothesis(empty_hypothesis, trans_opt)\n >>> # Added because identical but better score\n >>> stack.add(hypothesis)\n True\n \"\"\"\n idx, identical_hyp = 0, None\n for i, h in enumerate(self.hyps):\n if h.identical(hyp):\n identical_hyp = h\n idx = i\n # there can only be one hypothesis identical to\n # the one being added because there are no existing hypotheses\n # in the stack identical to one another\n break\n\n if identical_hyp and identical_hyp < hyp:\n del self.hyps[idx]\n\n if not identical_hyp or (identical_hyp and identical_hyp < hyp):\n\n if self.pruning_type is \"Histogram\":\n bisect.insort(self.hyps, hyp)\n\n # This is an example of 'Histogram pruning'\n # If the stack approaches its MAXSIZE, prune it by\n # removing (in this case) one hypothesis - the top\n # or worst scored element of the stack.\n if len(self.hyps) > self.size:\n del self.hyps[0]\n\n elif self.pruning_type is \"Threshold\":\n try:\n best_score = self.hyps[-1].trans['score'] + \\\n self.hyps[-1].future_cost\n\n # If the score of a hypothesis is 'threshold/alpha' times\n # worse than best, prune it If it is > alpha, we do not add\n # it.\n if (best_score / (hyp.future_cost + hyp.trans['score'])) \\\n < self.alpha:\n bisect.insort(self.hyps, hyp)\n except IndexError:\n bisect.insort(self.hyps, hyp)\n\n return True\n return False\n\n def hypotheses(self):\n \"\"\"Get all hypotheses in the stack.\"\"\"\n return self.hyps\n\n def best(self):\n \"\"\"Return the best hypotheses in the stack.\"\"\"\n try:\n return self.hyps[-1]\n except IndexError:\n return None\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","repo_name":"desmond86/CLIR2","sub_path":"src/phrase/datastructures.py","file_name":"datastructures.py","file_ext":"py","file_size_in_byte":8772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"74942986198","text":"from random import uniform, randint\n\n\nclass Pokemon:\n \"\"\"Pokemon Object\"\"\"\n\n def __init__(self, info):\n self.id = info[\"id\"]\n self.name = info[\"name\"]\n self.type = info[\"type\"]\n self.base_experience = info.get(\"base_experience\", 0)\n self.base_hp = info[\"base_hp\"]\n self.base_atk = info[\"base_atk\"]\n self.base_def = info[\"base_def\"]\n self.base_speed = info[\"base_speed\"]\n self.base_special_atk = info[\"base_special_atk\"]\n self.base_special_def = info[\"base_special_def\"]\n self.dmg_when_atked = info[\"dmg_when_atked\"]\n\n self.max_hp = info.get(\"max_hp\") or self.base_hp\n self.cur_hp = info.get(\"cur_hp\") or self.base_hp\n self.atk = info.get(\"atk\") or self.base_atk\n self.defense = info.get(\"defense\") or self.base_def\n self.speed = info.get(\"speed\") or self.base_speed\n self.special_atk = info.get(\"special_atk\") or self.base_special_atk\n self.special_def = info.get(\"special_def\") or self.base_special_def\n\n self.ev = info.get(\"ev\") or uniform(0.5, 1.0)\n self.accumulated_xp = info.get(\"accumulated_xp\") or 0\n self.level = info.get(\"level\") or 1\n self.required_xp = info.get(\"required_xp\") or self.base_experience\n\n if self.required_xp and self.level == 1:\n for _ in range(randint(0, 9)):\n self.gain_xp(self.required_xp)\n\n def total_xp(self):\n return (2**~-self.level-1)*self.base_experience + self.accumulated_xp\n\n def is_alive(self):\n return self.cur_hp > 0\n\n def level_up(self):\n self.accumulated_xp -= self.required_xp\n self.required_xp *= 2\n self.level += 1\n self.max_hp = int(round(self.max_hp*(1+self.ev)))\n self.cur_hp = self.max_hp\n self.atk = int(round(self.atk*(1+self.ev)))\n self.defense = int(round(self.defense*(1+self.ev)))\n self.speed = int(round(self.speed*(1+self.ev)))\n self.special_atk = int(round(self.special_atk*(1+self.ev)))\n self.special_def = int(round(self.special_def*(1+self.ev)))\n\n def take_dmg(self, dmg):\n self.cur_hp -= max(dmg - self.defense, 0)\n return max(dmg - self.defense, 0)\n\n def take_special_dmg(self, dmg, types):\n mul = 1.0\n for t in types:\n mul = max([x[\"multiply\"] for x in self.dmg_when_atked if x[\"type\"] == t] + [mul])\n self.cur_hp -= max(int(round(dmg*mul)) - self.special_def, 0)\n return max(int(round(dmg*mul)) - self.special_def, 0)\n\n def gain_xp(self, xp):\n self.accumulated_xp += xp\n while self.accumulated_xp >= self.required_xp:\n self.level_up()\n\n def serialize_xp(self):\n return {\"id\": self.id,\n \"name\": self.name,\n \"type\": self.type,\n \"base_experience\": self.base_experience,\n \"base_hp\": self.base_hp,\n \"base_atk\": self.base_atk,\n \"base_def\": self.base_def,\n \"base_speed\": self.base_speed,\n \"base_special_atk\": self.base_special_atk,\n \"base_special_def\": self.base_special_def,\n \"dmg_when_atked\": self.dmg_when_atked,\n \"max_hp\": self.max_hp,\n \"cur_hp\": self.cur_hp,\n \"atk\": self.atk,\n \"defense\": self.defense,\n \"special_atk\": self.special_atk,\n \"special_def\": self.special_def,\n \"ev\": self.ev,\n \"accumulated_xp\": self.accumulated_xp,\n \"level\": self.level,\n \"required_xp\": self.required_xp}\n\n def serialize(self):\n return {\"id\": self.id,\n \"name\": self.name,\n \"type\": self.type,\n \"base_experience\": self.base_experience,\n \"base_hp\": self.base_hp,\n \"base_atk\": self.base_atk,\n \"base_def\": self.base_def,\n \"base_speed\": self.base_speed,\n \"base_special_atk\": self.base_special_atk,\n \"base_special_def\": self.base_special_def,\n \"dmg_when_atked\": self.dmg_when_atked}\n","repo_name":"th1rt3en/Net-Centric","sub_path":"PokeApp/PokeServer/Pokemon.py","file_name":"Pokemon.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"43117977166","text":"import re\r\nimport os\r\nimport urllib.request\r\nfrom bs4 import BeautifulSoup\r\nimport csv\r\nfrom urllib.request import Request, urlopen\r\nimport random\r\n# import some geomodule\r\n\r\ndef decode_month(word):\r\n months = {\r\n 'Jan': 0,\r\n 'Feb': 1,\r\n 'Mar': 2,\r\n 'Apr': 3,\r\n 'May': 4,\r\n 'Jun': 5,\r\n 'Jul': 6,\r\n 'Aug': 7,\r\n 'Sep': 8,\r\n 'Oct': 9,\r\n 'Nov': 10,\r\n 'Dec': 11}\r\n month = months[word]\r\n return month\r\n\r\n# создает файл для записи результатов,\r\n# если его не было до этого\r\ndef create_output_file(output_file, fields):\r\n with open(output_file, 'w', encoding='utf-8', newline='') as csvfile:\r\n writer = csv.DictWriter(\r\n csvfile, delimiter=';',\r\n fieldnames=fields)\r\n writer.writeheader()\r\n\r\n\r\n# записывает строку данных в файл\r\ndef write_data_down(output_file, fields, full_title,link,location,start_day,start_month,start_year,end_day,end_month,end_year,tags,site,cd_day,cd_month,cd_year):\r\n with open(output_file, 'a', encoding='utf-8', newline='') as csvfile:\r\n writer = csv.DictWriter(\r\n csvfile, delimiter=';',\r\n fieldnames=fields)\r\n writer.writerow({'full_title': full_title,'link': link,'location': location,\r\n 'start_day': start_day,'start_month': start_month,'start_year': start_year,\r\n 'end_day': end_day,'end_month': end_month,'end_year': end_year,\r\n 'tags': tags,'site': site,\r\n 'cd_day': cd_day,'cd_month': cd_month,'cd_year': cd_year})\r\n \r\n#достает ссылку на страницу конференции со страницы со списком конференций \r\ndef extract_main_info(conf_raw): \r\n name_raw = re.search('((.|\\n)*?)<', conf_raw[0])\r\n name = name_raw.group(2).strip()\r\n link_raw = name_raw.group(1)\r\n link = 'https://linguistlist.org/' + link_raw[3:]\r\n print(link)\r\n meta = re.search('\\[(.*?)] \\[(.*?) - (.*?)]<', conf_raw[0])\r\n place = meta.group(1)\r\n \r\n start_date_raw = meta.group(2)\r\n start_date_raw = start_date_raw.split('-')\r\n start_day = start_date_raw[0]\r\n start_month = decode_month(start_date_raw[1])\r\n start_year = start_date_raw[2]\r\n \r\n end_date_raw = meta.group(3)\r\n end_date_raw = end_date_raw.split('-')\r\n end_day = end_date_raw[0]\r\n end_month = decode_month(end_date_raw[1])\r\n end_year = end_date_raw[2]\r\n \r\n return name, link, place, start_day, start_month, start_year, end_day, end_month, end_year\r\n\r\ndef extract_details(link):\r\n try:\r\n req = Request(link, headers={'User-Agent': 'Mozilla/5.0'})\r\n #connect to that page\r\n f = urlopen(req)\r\n except urllib.error.HTTPError:\r\n print('An Error occured')\r\n else:\r\n #read it all in\r\n myfile = f.read().decode('utf-8')\r\n #build a document model\r\n soup = BeautifulSoup(myfile,'html.parser')\r\n #print(soup)\r\n #full_title = re.search('Full Title: (.*?)
', str(soup), re.DOTALL).group(1).strip()\r\n\r\n '''start_date, end_date = re.search('Date: (.*?)
', str(soup)).group(1).strip().split(' - ')\r\n \r\n start_date= start_date.split('-')\r\n start_day = start_date[0]\r\n start_month = decode_month(start_date[1])\r\n start_year = start_date[2]\r\n \r\n end_date = end_date.split('-')\r\n end_day = end_date[0]\r\n end_month = decode_month(end_date[1])\r\n end_year = end_date[2]\r\n \r\n if re.search('Location: (.*?)
', str(soup)):\r\n location = re.search('Location: (.*?)
', str(soup)).group(1).strip()\r\n else:\r\n location = 'Unknown'''\r\n \r\n if re.search('Linguistic Field\\(s\\): (.*?)
', str(soup)):\r\n tags = ', '.join(re.search('Linguistic Field\\(s\\): (.*?)
', str(soup)).group(1).strip().split('; '))\r\n else:\r\n tags = 'None'\r\n \r\n if re.search('Web Site:
', str(soup)):\r\n call_deadline = re.search('Call Deadline: (.*?)
', str(soup)).group(1).strip().split('-')\r\n cd_day = call_deadline[0]\r\n cd_month = decode_month(call_deadline[1])\r\n cd_year = call_deadline[2] \r\n else:\r\n cd_day, cd_month, cd_year = 'None', 'None', 'None'\r\n return tags,site,cd_day,cd_month,cd_year\r\n\r\n# тут все сразу\r\ndef main():\r\n link = 'https://linguistlist.org/callconf/browse-current.cfm?type=Conf'\r\n output_file = 'results.csv'\r\n fields = ['full_title','link','location','start_day','start_month','start_year','end_day','end_month','end_year','tags','site','cd_day','cd_month','cd_year']\r\n\r\n #создает файл, если его нет\r\n create_output_file(output_file, fields)\r\n\r\n #открывает сайт\r\n try:\r\n req = Request(link, headers={'User-Agent': 'Mozilla/5.0'})\r\n #connect to that page\r\n f = urlopen(req)\r\n except urllib.error.HTTPError:\r\n print('An Error occured')\r\n else:\r\n #read it all in\r\n myfile = f.read().decode('utf-8')\r\n #build a document model\r\n soup = BeautifulSoup(myfile,'html.parser')\r\n #парсит сайт\r\n all_conf_raw = re.findall('((.|\\n)*?)<\\/td>', str(soup))\r\n if len(all_conf_raw) > 1:\r\n for conf_raw in all_conf_raw[1:]: #именно с 1! можно ограничить кол-во\r\n conf_name, conf_link, place, sday, smonth, syear, eday, emonth, eyear = extract_main_info(conf_raw)\r\n tags,site,cd_day,cd_month,cd_year = extract_details(conf_link)\r\n \r\n #записывает строчку в файл\r\n write_data_down(\r\n output_file,fields,conf_name,conf_link,place,sday,smonth,syear,eday,emonth,eyear,tags,site,cd_day,cd_month,cd_year) \r\n else:\r\n print('an error occured')\r\n print('All done.')\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"polyankaglade/DH-project-2","sub_path":"code/data_extraction_kinda_final.py","file_name":"data_extraction_kinda_final.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34116053742","text":"\"\"\"\n A self-dividing number is a number that is divisible by every digit it \n contains.\n For example, 128 is a self-dividing number because 128 % 1 == 0, \n 128 % 2 == 0, and 128 % 8 == 0.\n Also, a self-dividing number is not allowed to contain the digit zero.\n Given a lower and upper number bound, output a list of every possible self \n dividing number, including the bounds if possible.\n\n Example:\n Input: \n left = 1, right = 22\n Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]\n\n Note:\n - The boundaries of each input argument are 1 <= left <= right <= 10000.\n\"\"\"\n#Difficulty: Easy\n#31 / 31 test cases passed.\n#Runtime: 36 ms\n#Memory Usage: 14.1 MB\n\n#Runtime: 36 ms, faster than 98.67% of Python3 online submissions for Self Dividing Numbers.\n#Memory Usage: 14.1 MB, less than 5.05% of Python3 online submissions for Self Dividing Numbers.\n\nclass Solution:\n \n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n result = []\n for number in range(left, right+1):\n number = self.selfDividingNumber(number)\n if number:\n result.append(number)\n return result\n\n def selfDividingNumber(self, number):\n temp = number\n while temp:\n n = temp % 10\n temp //= 10\n if n == 0 or number % n:\n return\n return number\n","repo_name":"YuriSpiridonov/LeetCode","sub_path":"Easy/728.SelfDividingNumbers.py","file_name":"728.SelfDividingNumbers.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"85"} +{"seq_id":"1106291542","text":"#!/usr/bin/env python\nimport yt\nimport numpy as np\nimport matplotlib.pylab as pl\n\nfrom yt.visualization.api import Streamlines\nfrom yt.units import cm\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Load the dataset\nds = yt.load('wd_512_rhoc4-5_plt64636')\n\n# Define c: the center of the box, N: the number of streamlines,\n# scale: the spatial scale of the streamlines relative to the boxsize,\n# and then pos: the random positions of the streamlines.\nc = ds.domain_center\nN = 100\nscale = ds.domain_width[0]\npos_dx = np.random.random((N,3))*scale\npos = pos_dx\n\n# Create streamlines of the 3D vector velocity and integrate them through\n# the box defined above\nstreamlines = Streamlines(ds, pos, ('boxlib', 'x_vel'), ('boxlib', 'y_vel'), ('boxlib', 'z_vel'), get_magnitude=True, volume=ds.all_data())\nstreamlines.integrate_through_volume()\n\n# Create a 3D plot, trace the streamlines throught the 3D volume of the plot\nfig=pl.figure()\nax = Axes3D(fig)\nfor stream in streamlines.streamlines:\n stream = stream[np.all(stream != 0.0, axis=1)]\n ax.plot3D(stream[:,0], stream[:,1], stream[:,2], alpha=0.1)\n\n# Save the plot to disk.\npl.savefig('vel_streamlines.png')\n","repo_name":"AMReX-Astro/MAESTRO","sub_path":"Util/postprocessing/urca-tools/streamlines.py","file_name":"streamlines.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"85"} +{"seq_id":"73542468438","text":"from math import sqrt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass NormalizingFlow(nn.Module):\n \"\"\"General implementation of a normalizing flow.\n\n Normalizing flows apply a series of maps to a latent variable.\n\n NOTE: Keyword arguments are passed to the maps.\n\n Args:\n dim: Dimension of the latent variable.\n map_type: Type of map applied at each step of the flow. One of\n 'planar', 'linear', 'resnet'.\n K: Number of maps to apply.\n \"\"\"\n def __init__(self, dim, map_type, K, **kwargs):\n super(NormalizingFlow, self).__init__()\n\n self.dim = dim\n self.map_type = map_type\n self.K = K\n\n if map_type == 'planar':\n map = PlanarMap\n elif map_type == 'radial':\n map = RadialMap\n elif map_type == 'linear':\n map = LinearMap\n elif map_type == 'resnet':\n raise NotImplementedError('ResnetMap not currently implemented.')\n else:\n raise ValueError('Unknown `map_type`: %s' % map_type)\n\n self.maps = nn.ModuleList([map(dim, **kwargs) for _ in range(K)])\n\n def forward(self, z, h):\n \"\"\"Computes forward pass of the planar flow.\n\n Args:\n z: torch.Tensor(batch_size, dim). The latent variable.\n\n Returns:\n f_z: torch.Tensor(batch_size, dim). The output of the final map\n sum_logdet: scalar. The sum of the log-determinants of the\n transformations.\n \"\"\"\n f_z = z\n sum_logdet = 0.0\n for map in self.maps:\n f_z, logdet = map(f_z, h)\n sum_logdet += logdet\n return f_z, sum_logdet\n\n\nclass Map(nn.Module):\n \"\"\"Generic parent class for maps used in a normalizing flow.\n\n Args:\n dim: Dimensionality of the latent variable.\n \"\"\"\n def __init__(self, dim):\n super(Map, self).__init__()\n self.dim = dim\n\n def forward(self, z, h):\n \"\"\"Computes the forward pass of the map.\n\n This method should be implemented for each subclass of Map. This\n function should always have the following signature:\n\n Args:\n z: torch.Tensor(batch_size, dim).\n The latent variable.\n\n Returns:\n f_z: torch.Tensor(batch_size, dim).\n The transformed latent variable.\n logdet: scalar.\n The log-determinant of the transformation.\n \"\"\"\n raise NotImplementedError\n\n\nclass PlanarMap(Map):\n \"\"\"The map used in planar flows, as described in:\n\n 'Variational Inference with Normalizing Flows'\n Rezende and Mohamed, ICML 2015\n\n Args:\n dim: Dimensionality of the latent variable.\n \"\"\"\n def __init__(self, dim):\n super(PlanarMap, self).__init__(dim=dim)\n\n self.u = torch.nn.Parameter(torch.Tensor(1, dim))\n self.w = torch.nn.Parameter(torch.Tensor(1, dim))\n self.b = torch.nn.Parameter(torch.Tensor(1))\n\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"Resets planar map parameters.\"\"\"\n a = sqrt(6 / self.dim)\n\n self.u.data.uniform_(-a, a)\n self.w.data.uniform_(-a, a)\n self.b.data.uniform_(-a, a)\n\n def forward(self, z, h):\n \"\"\"Computes forward pass of the planar map.\n\n Args:\n z: torch.Tensor(batch_size, dim).\n The latent variable.\n\n Returns:\n f_z: torch.Tensor(batch_size, dim).\n The transformed latent variable.\n logdet: scalar.\n The log-determinant of the transformation.\n \"\"\"\n # Ensure invertibility using approach in appendix A.1\n wu = torch.matmul(self.u, self.w.t()).squeeze()\n mwu = F.softplus(wu) - 1\n u_hat = self.u + (mwu - wu) * self.w / torch.sum(self.w**2)\n\n # Compute f_z using Equation 10.\n wz = torch.matmul(self.w, z.unsqueeze(2))\n wz.squeeze_(2)\n f_z = z + self.u * F.tanh(wz + self.b)\n\n # Compute psi using Equation 11.\n psi = self.w * (1 - F.tanh(wz + self.b)**2)\n\n # Compute logdet using Equation 12.\n logdet = torch.log(torch.abs(1 + torch.matmul(psi, self.u.t())))\n\n return f_z, logdet\n\n\nclass RadialMap(Map):\n \"\"\"The map used in radial flows, as described in:\n\n 'Variational Inference with Normalizing Flows'\n Rezende and Mohamed, ICML 2015\n\n Args:\n dim: Dimensionality of the latent variable.\n \"\"\"\n def __init__(self, dim):\n super(RadialMap, self).__init__(dim=dim)\n\n self.z0 = torch.nn.Parameter(torch.Tensor(1, dim))\n self.alpha = torch.nn.Parameter(torch.Tensor(1))\n self.beta = torch.nn.Parameter(torch.Tensor(1))\n\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"Resets radial map parameters.\"\"\"\n a = sqrt(6 / self.dim)\n\n self.z0.data.uniform_(-a, a)\n self.alpha.data.uniform_(-a, a)\n self.beta.data.uniform_(-a, a)\n\n def forward(self, z, h):\n \"\"\"Computes forward pass of the radial map.\n\n Args:\n z: torch.Tensor(batch_size, dim).\n The latent variable.\n\n Returns:\n f_z: torch.Tensor(batch_size, dim).\n The transformed latent variable.\n logdet: scalar.\n The log-determinant of the transformation.\n \"\"\"\n # Ensure invertibility using approach in appendix A.2\n beta_prime = -self.alpha + F.softplus(self.beta)\n\n # Compute f_z and logdet using Equation 14.\n diff = z - self.z0\n r = diff.norm(p=2, dim=1, keepdim=True)\n h = 1 / (self.alpha + r)\n dh = - (h ** 2)\n\n f_z = z + beta_prime * h * diff\n det = (1 + beta_prime * h)**(self.dim - 1) * (1 + beta_prime * h + beta_prime * dh * r)\n logdet = torch.log(det)\n\n return f_z, logdet\n\n\nclass LinearMap(Map):\n \"\"\"The map used in linear IAF step, as described in:\n\n 'Improved Variational Inference with Inverse Autoregressiev Flow'\n Kingma, Salimans, Jozefowicz, Chen, Sutskever, and Welling, NIPS 2016\n\n Args:\n dim: Dimensionality of the latent variable.\n \"\"\"\n def __init__(self, dim):\n super(LinearMap, self).__init__(dim=dim)\n self.cuda_available = torch.cuda.is_available()\n\n def forward(self, z, h):\n \"\"\"Computes forward pass of the linear map.\n\n Args:\n z: torch.Tensor(batch_size, dim).\n The latent variable.\n\n Returns:\n f_z: torch.Tensor(batch_size, dim).\n The transformed latent variable.\n logdet: scalar.\n The log-determinant of the transformation.\n \"\"\"\n batch_size = z.shape[0]\n\n # Compute f_z using Equation in Appendix A.\n l_mat = torch.zeros(batch_size, self.dim, self.dim)\n if torch.cuda.is_available():\n l_mat = l_mat.cuda()\n k = 0\n for i in range(self.dim):\n for j in range(0, i + 1):\n l_mat[:, i, j] = h[:, k] if j < i else 1\n if i != j:\n k += 1\n f_z = torch.matmul(l_mat, z.unsqueeze(2)).squeeze()\n return f_z, torch.zeros(1).to('cuda' if self.cuda_available else 'cpu')\n\n","repo_name":"dDua/SentenceIAF","sub_path":"modules/normalizing_flow.py","file_name":"normalizing_flow.py","file_ext":"py","file_size_in_byte":7307,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"31275556142","text":"\n# Renames all files in a folder using names from a text file\n \nimport sublime, sublime_plugin\nimport os, re, codecs\n\nfrom user_modules.file_system_functions import *\nfrom user_modules.general_functions import *\n\n\nclass RenameFilesFromListCommand(sublime_plugin.WindowCommand):\n def run(self):\n source_list = \"path\\\\to\\\\file\"\n dir_dest = \"path\\\\to\\\\folder\"\n \n filenames_src = []\n \n file = codecs.open(source_list, encoding='utf-8', mode='r')\n \n for line in file:\n line = line.rstrip('\\r\\n')\n line = normalize_filename(line)\n filenames_src.append(line)\n \n filenames_dest = get_filenames(dir_dest)\n \n i = 0\n \n for dest_file in filenames_dest:\n source_file = filenames_src[i]\n \n source_name, source_ext = os.path.splitext(source_file)\n dest_name, dest_ext = os.path.splitext(dest_file)\n \n from_name = dir_dest + \"\\\\\" + dest_file\n to_name = dir_dest + \"\\\\\" + source_name + dest_ext\n \n os.rename(from_name, to_name)\n \n i += 1\n \n print('finish')\n ","repo_name":"mortalis13/UserSettings","sub_path":"SublimeText/user_plugins/rename_files_from_list.py","file_name":"rename_files_from_list.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17433905594","text":"# Objective: \n'''\n• When executed, script must:\n1. Slowly (user-define “slowly”)\ncycle gripper from open to closed\nand back again\n2. Record an image with the RPi\ncamera at each gripper position\n3. Print duty cycle onto each image\n4. Stich images together to generate\ntime-lapse video\n'''\n# import the necessary packages\nimport os\nimport RPi.GPIO as GPIO\nimport time\nimport numpy as np\nimport cv2\nimport imutils\n\n# Function to take a snapshot from RPi\ndef TakeImgRPi(name):\n print(\"Taking a picture..\")\n os.system('raspistill -w 640 -h 480 -o ' + name)\n time.sleep(0.5)\n image = cv2.imread(name)\n #cv2.imshow(name, image)\n #cv2.waitKey(1)\n return image\n\n# Function to calculate instantaneous distance\ndef distance():\n # Generate trigger pulse\n GPIO.output(trig, True)\n time.sleep(0.00001)\n GPIO.output(trig, False)\n\n # Generate echo time signal\n while GPIO.input(echo) == 0:\n pulse_start = time.time()\n \n while GPIO.input(echo) == 1:\n pulse_end = time.time()\n \n pulse_duration = pulse_end - pulse_start\n\n # Convert time to distance\n distance = pulse_duration * 17150\n distance = round(distance, 2)\n\n return distance\n\n# Function to calculate average distance (takes 2 seconds)\ndef AvgDistance(num_of_readings):\n\n average_dist = np.array([])\n distances = []\n\n for i in range(num_of_readings):\n inst_val = distance()\n #print(\"Distance: \", inst_val, \"cm\")\n distances.append(inst_val)\n time.sleep(0.5)\n \n avg_dist = round(np.average(distances),2)\n print(\"Average distance to the obstacle: \",avg_dist,\" cm\")\n return avg_dist\n\n# Function to rotate servo to the required position (takes 2 seconds)\ndef ServoControl(pos):\n if pos == \"full_closed\":\n duty_cycle = 3.3\n pwm.ChangeDutyCycle(duty_cycle) \n time.sleep(2)\n elif pos == \"partial_open\":\n duty_cycle = 5.5\n pwm.ChangeDutyCycle(duty_cycle)\n time.sleep(2)\n elif pos == \"full_open\":\n duty_cycle = 7.5\n pwm.ChangeDutyCycle(duty_cycle)\n time.sleep(2)\n else:\n duty_cycle = 3.3\n pwm.ChangeDutyCycle(duty_cycle)\n time.sleep(2)\n \n return duty_cycle\n \n \n# Read Image, add text, save, and display for 1 second\ndef WriteTextOnImg(img, text, pos):\n gImage = cv2.imread(img)\n font = cv2.FONT_HERSHEY_COMPLEX_SMALL\n clr = (0, 255, 0)\n if pos == \"L\":\n orig = (20, 20)\n else:\n orig = (405, 20)\n cv2.putText(gImage, text, orig, font, 1, clr, 1)\n cv2.imwrite(img, gImage)\n #cv2.imshow(img, image)\n #cv2.waitKey(1) \n\n###### End of Function definitions #############\n\n#------- Main Function ------------#\nprint(\"Ensure the Power Switch is ON ...\")\ntime.sleep(5)\n\n# Distance Measurement - Define pin allocations\nGPIO.setmode(GPIO.BOARD)\ntrig = 16\necho = 18\nGPIO.setup(trig, GPIO.OUT)\nGPIO.setup(echo, GPIO.IN)\n# Servo Control - Define pin allocations\nGPIO.setup(36, GPIO.OUT)\n\n# Distance Measure - Initialize - Ensure output has no value\nGPIO.output(trig, False)\ntime.sleep(0.01)\n\n# Servo Control - Initialize PWM\npwm = GPIO.PWM(36, 50)\npwm.start(5)\n\n######### Gripper to Full-closed Position ##########\n# Move the gripper to Full- Closed position (2 sec)\nprint(\"Moving the gripper to Full-Closed position\")\nduty = ServoControl(\"full_closed\")\n# Take a snapshot of Gripper position from RPi Camera\n# and save it to a jpg file (0.5 sec)\nname_image = \"Gripper_Full_Closed_Pos_init.jpg\"\nimage = TakeImgRPi(name_image)\n# Calculate the avg. distance of an object (4 samples - 2 seconds)\nprint(\"Calculating the distance to the obstacle...\")\navg_distance = AvgDistance(4)\n# Dispaly the average distance on the captured image and save (1 sec)\ntext = \"Distance: \" + str(avg_distance) + \" cm\"\nWriteTextOnImg(name_image,text,\"R\")\ntext = \"Duty Cycle: \" + str(duty) + \"%\"\nWriteTextOnImg(name_image,text,\"L\")\nprint(\"-------\")\n\n######### Gripper to Partially-Open Position ##########\n# Move the gripper to Partially-Open position\nprint(\"Moving the gripper to Partially-Open position\")\nduty = ServoControl(\"partial_open\")\n# Take a snapshot of Gripper position from RPi Camera\n# and save it to a jpg file\nname_image = \"Gripper_Partial_Open_Pos.jpg\"\nimage = TakeImgRPi(name_image)\n# Calculate the avg. distance of an object (4 samples - 2 seconds)\nprint(\"Calculating the distance to the obstacle...\")\navg_distance = AvgDistance(4)\n# Dispaly the average distance on the captured image and save\ntext = \"Distance: \" + str(avg_distance) + \" cm\"\nWriteTextOnImg(name_image,text,\"R\")\ntext = \"Duty Cycle: \" + str(duty) + \"%\"\nWriteTextOnImg(name_image,text,\"L\")\nprint(\"-------\")\n\n######### Gripper to Full-Open Position ##########\n# Move the gripper to Full- Open position\nprint(\"Moving the gripper to Full- Open position\")\nduty = ServoControl(\"full_open\")\n# Take a snapshot of Gripper position from RPi Camera\n# and save it to a jpg file\nname_image = \"Gripper_Full_Open_Pos.jpg\"\nimage = TakeImgRPi(name_image)\n# Calculate the avg. distance of an object (4 samples - 2 seconds)\nprint(\"Calculating the distance to the obstacle...\")\navg_distance = AvgDistance(4)\n# Dispaly the average distance on the captured image and save\ntext = \"Distance: \" + str(avg_distance) + \" cm\"\nWriteTextOnImg(name_image,text,\"R\")\ntext = \"Duty Cycle: \" + str(duty) + \"%\"\nWriteTextOnImg(name_image,text,\"L\")\nprint(\"-------\")\n\n######### Gripper to Full-closed Position ##########\n# Move the gripper to Full- Closed position\nprint(\"Moving the gripper to Full- Closed position\")\nduty = ServoControl(\"full_closed\")\n# Take a snapshot of Gripper position from RPi Camera\n# and save it to a jpg file\nname_image = \"Gripper_Full_Closed_Pos_final.jpg\"\nimage = TakeImgRPi(name_image)\n# Calculate the avg. distance of an object (4 samples - 2 seconds)\nprint(\"Calculating the distance to the obstacle...\")\navg_distance = AvgDistance(4)\n# Dispaly the average distance on the captured image and save\ntext = \"Distance: \" + str(avg_distance) + \" cm\"\nWriteTextOnImg(name_image,text,\"R\")\ntext = \"Duty Cycle: \" + str(duty) + \"%\"\nWriteTextOnImg(name_image,text,\"L\")\nprint(\"-------\")\n# Stope Servo\npwm.stop()\n# Cleanup GPIO pins\nGPIO.cleanup()","repo_name":"Arshad-Engineer/Autonomous-Robotics---Pick-n-Place-using-Servo-Gripper-","sub_path":"servocontrol01.py","file_name":"servocontrol01.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5088685928","text":"# Checks for any reservations made by the user in the current day the timeslot is in\ndef reservation_exists(user, timeslot):\n customer = user.customer\n day = timeslot.day\n # tslots stands for timeslots\n day_tslots = day.timeslot_set.all()\n\n # tslot stands for timeslot\n tslot = day_tslots[0]\n tslot_reservations = timeslot.reservation_set.all()\n\n res_exists = False\n i = 0\n while res_exists is False and i < len(day_tslots):\n n = 0\n while n < len(tslot_reservations) and res_exists == False:\n reservation = tslot_reservations[n]\n if reservation.customer == customer:\n res_exists = True\n n += 1\n\n i += 1\n tslot = day_tslots[i]\n timesloslot_reservations = timeslot.reservation_set.all()\n\n i = 0\n\n return res_exists","repo_name":"ObiTracks/BloomV1","sub_path":"src/reservations/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"37492447352","text":"try:\n import pexpect\n from pexpect.popen_spawn import PopenSpawn\nexcept ModuleNotFoundError:\n print(\"Module pexpect is not installed\")\n exit\nimport time\nimport shutil\n\nif shutil.which(\"plink\") != None:\n print(\"plink is installed\")\nelse:\n print(\"plink is not installed\")\n print(\"run winget install putty.putty to install it from terminal\")\n exit\n \nssh_tunnel = pexpect.popen_spawn.PopenSpawn('plink username@IPADDRESS -pw password -batch', encoding='utf-8')\ntime.sleep(5)\nssh_tunnel.sendline('reboot')\ntime.sleep(5)\nssh_tunnel.sendline('y')\ntime.sleep (5)\nssh_tunnel.expect(pexpect.EOF)\nexit\n","repo_name":"Griffen8280/Unifi-Device-Rebooter","sub_path":"rebooter.py","file_name":"rebooter.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"71029053060","text":"# Exam 1 Practice\n# Question Number 2\n# Biking Mileage\n\n# Initialize variables\nnew_day = float(input('How many miles did you ride on day 1? '))\ntotal_miles = 0\nday = 1\n\n# Runs a loop until the user doesn't input anything\nwhile new_day != '':\n new_day = float(new_day)\n if new_day >= 0:\n total_miles += new_day\n day += 1\n new_day = input('How many miles did you ride on day ' + str(day) + '? (Leave blank to end) ')\n\n# Returns the total number of miles\nprint('You rode a total of', total_miles, 'miles!')\n","repo_name":"iccowan/CSC_117","sub_path":"exam_1_practice/number_2.py","file_name":"number_2.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"27810074805","text":"a=int(input(\"Enter the first number : \"))\r\nb=int(input(\"Enter the secont number : \"))\r\nc=int(input(\"Enter the third number : \"))\r\n\r\nif(a==b==c):\r\n print(\"All values are same\")\r\nelif(a==b):\r\n if(c>a or c>b):\r\n print(\"a and b are equal and c is greater\")\r\n else:\r\n print(\"a and b are equal and c is lesser\")\r\nelif(a==c):\r\n if(b>a or b>c):\r\n print(\"a and b are equal and c is greater\")\r\n else:\r\n print(\"a and b are equal and c is lesser\")\r\nelif(b==c ):\r\n if(a>b or a>c):\r\n print(\"a and b are equal and c is greater\")\r\n else:\r\n print(\"a and b are equal and c is lesser\")\r\nelif(a>b and a>c):\r\n print(a,\"is greater than\",b,\"and\",c)\r\nelif(b>a and b>c):\r\n print(b,\"is greater than\",a,\"and\",c)\r\nelse:\r\n print(c,\"is greater than\",a,\"and\",b)\r\n","repo_name":"sagar9753/python-practice-program","sub_path":"Greater_num_bw_3_nums.py","file_name":"Greater_num_bw_3_nums.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16778791089","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport torch\nimport torchvision\nimport finetune\nimport os\nimport cv2\nimport numpy as np\nimport time\nimport gpustat\nimport threading\nimport queue\nimport glob\n\nfrom util import constant as c\n\n# for tissue data\nDATA_DIR = c.QDATA_DIR\nSUPP_DATA_DIR = c.SUPP_DATA_DIR\nTISSUE_DIR = c.TISSUE_DIR\nFV_DIR = c.FV_DIR\n\n\ndef get_gpu_usage(device=1):\n gpu_stats = gpustat.new_query()\n item = gpu_stats.jsonify()[\"gpus\"][device]\n return item['memory.used'] / item['memory.total']\n\n\ndef get_gene_list():\n pattern = \"%s/**/*.txt\" % TISSUE_DIR\n genes = [os.path.splitext(os.path.basename(x))[0]\n for x in glob.glob(pattern)]\n return list(set(genes))\n\n\ndef get_gene_pics(gene):\n pics = []\n for t in ['liver', 'breast', 'prostate', 'bladder']:\n tp = os.path.join(TISSUE_DIR, t, \"%s.txt\" % gene)\n if os.path.exists(tp):\n with open(tp, 'r') as f:\n pics.extend([l.strip(\"\\n\") for l in f.readlines()])\n return pics\n\n\ndef extract_image_fv(q, model, i):\n\n def _extract_image(image):\n\n img = cv2.imread(image)\n img = cv2.resize(img, (3000, 3000), interpolation=cv2.INTER_CUBIC)\n img = np.transpose(img, (2, 0, 1))\n img = np.expand_dims(img, axis=0)\n # return img\n\n inputs = torch.from_numpy(img).type(torch.cuda.FloatTensor)\n pd = model(inputs)\n return pd\n\n while True:\n\n while get_gpu_usage() > 0.9:\n print(\"---gpu full---\", get_gpu_usage())\n time.sleep(1)\n torch.cuda.empty_cache()\n\n gene = q.get()\n if gene is None:\n break\n print(\"---extract -----\", gene, q.qsize(), i)\n gene_dir = os.path.join(DATA_DIR, gene)\n if not os.path.exists(gene_dir):\n gene_dir = os.path.join(SUPP_DATA_DIR, gene)\n\n outpath = os.path.join(FV_DIR, \"%s.npy\" % gene)\n if os.path.exists(outpath):\n print(\"------already extracted---------\", gene)\n q.task_done()\n continue\n\n pds = [_extract_image(os.path.join(gene_dir, p))\n for p in get_gene_pics(gene)\n if os.path.splitext(p)[-1] == \".jpg\"]\n if pds:\n value = np.concatenate(pds, axis=0)\n print(\"----save-----\", outpath)\n np.save(outpath, value)\n q.task_done()\n\n\ndef extract():\n q = queue.Queue()\n for gene in get_gene_list():\n q.put(gene)\n\n resnet18 = torchvision.models.resnet18(pretrained=True)\n model = finetune.FineTuneModel(resnet18)\n for param in model.parameters():\n param.requires_grad = False\n model.share_memory()\n model.cuda()\n # print(model)\n\n jobs = []\n for i in range(8):\n p = threading.Thread(target=extract_image_fv, args=(q, model, i))\n jobs.append(p)\n p.start()\n\n q.join()\n\n for i in range(8):\n q.put(None)\n\n for j in jobs:\n j.join()\n\n\nif __name__ == \"__main__\":\n # get_gene_list()\n extract()\n","repo_name":"yl2019lw/ImPloc","sub_path":"extractor/tissue_res18_fv.py","file_name":"tissue_res18_fv.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"80"} +{"seq_id":"33015787106","text":"# ----------------------------------------------------------------------------\n# This contract is an example of an acurast consumer on Tezos blockchain.\n#\n# It allows contracts to receive job fulfillments from Acurast processors.\n# ----------------------------------------------------------------------------\n\nimport smartpy as sp\n\n\nclass Entrypoint:\n Fulfill = \"fulfill\"\n\n\nclass Type:\n Fulfill = sp.TRecord(job_id=sp.TNat, payload=sp.TBytes).right_comb()\n\n\nclass Inlined:\n @staticmethod\n def failIfNotAcurastProxy(self):\n \"\"\"\n This method when used, ensures that only the acurast contract is allowed to call a given entrypoint\n \"\"\"\n sp.verify(self.data.config.acurast_proxy == sp.sender, \"NOT_ACURAST_PROXY\")\n\n\nclass AcurastConsumer(sp.Contract):\n def __init__(self):\n self.init_type(\n sp.TRecord(\n config=sp.TRecord(\n acurast_proxy=sp.TAddress,\n )\n # Add custom storage here ...\n )\n )\n\n @sp.entry_point(name=Entrypoint.Fulfill, parameter_type=Type.Fulfill)\n def fulfill(self, arg):\n Inlined.failIfNotAcurastProxy(self)\n\n # Process fulfill payload ...\n payload = arg.payload\n","repo_name":"Acurast/acurast-hyperdrive","sub_path":"contracts/tezos/AcurastConsumer.py","file_name":"AcurastConsumer.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"34495219946","text":"#!/usr/bin/python3\n# \n\nfrom jinja2 import Template, Environment, FileSystemLoader\nimport os, sys, pynetbox\n\n\nusage = \"\"\"Usage: python3 netbox2blackbox.py [netbox_ip] [API Token] [device_roles] [output_file]\ne.g. python3 netbox2blackbox.py 10.0.0.10:32769 Gdstwt53t6gdsTGSXHey ats /etc/prometheus/file_sd/targets.yml\"\"\"\n\nif len(sys.argv) != 5:\n print(usage)\n sys.exit(0)\n\nnetbox_url = 'http://' + sys.argv[1]\ntoken = sys.argv[2]\n# What device types export to targets.yml\nrole = sys.argv[3]\ntarget_file = sys.argv[4]\n\n# Fetch device list from NetBox\ntry:\n nb = pynetbox.api(url=netbox_url, token=token)\nexcept pynetbox.core.query.RequestError as error:\n print(error.error)\n sys.exit(1)\n\ndata = '''\n#\n# Managed by netbox2prom.py. DON'T EDIT THIS FILE!!!\n#\n\n{% for device in devices %}\n- labels:\n nb_name: \"{{ device.nb_name }}\"\n nb_physical_address: \"{{ device.nb_physical_address }}\"\n targets: [{{ device.address }}]\n{% endfor %}\n'''\n\ntemplate = Template(data)\n# Select devices by role\ndev_group = nb.dcim.devices.filter(role=role)\n\n# Make config from template\ndevices = []\nfor device in dev_group:\n if str(device.status) == \"Active\":\n target = {}\n target['nb_physical_address'] = device.site.physical_address\n target['nb_name'] = device.name\n target['address'] = str(device.primary_ip)[:-3]\n devices.append(target)\n \nconfig = template.render(devices=devices)\n#print(config)\nwith open(target_file, 'w') as file:\n file.write(config)","repo_name":"bubnovd/netbox_automation","sub_path":"netbox2prom/netbox2blackbox/netbox2blackbox.py","file_name":"netbox2blackbox.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"73251991297","text":"#! /usr/bin/python2.7\n\nimport socket\nimport Queue\nimport sys\nimport ipcMessage_pb2\nimport chat\nfrom thread import *\nfrom galatea.galatea import Galatea\n\nclass Slave():\n def __init__(self, port, logger):\n\n self._logger = logger\n\n self._logger.info(\"Slave init start\")\n\n self.host = ''\n self.port = port\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n self._logger.info(\"Slave init sockets\")\n\n self.chatDict = dict()\n\n self._logger.info(\"Slave init start nn\")\n self.load_nn()\n self._logger.info(\"Slave init end nn\")\n\n self.socket.bind((self.host, self.port))\n self.socket.listen(10)\n\n self._logger.info(\"Slave listening to socket\")\n\n while 1:\n conn, addr = self.socket.accept()\n\n start_new_thread(self.handleConn ,(conn,))\n\n self.socket.close()\n\n def load_nn(self):\n self.g = Galatea()\n\n\n def handleConn(self, conn):\n\n data = conn.recv(4096)\n if data:\n hello = ipcMessage_pb2.Hello()\n hello.ParseFromString(data)\n\n if not hello.response:\n respHello = ipcMessage_pb2.Hello()\n respHello.response = True\n\n conn.send(respHello.SerializeToString())\n\n while True:\n\n #Receiving from client\n data = conn.recv(4096)\n if not data:\n break\n\n msg = ipcMessage_pb2.Message()\n msg.ParseFromString(data)\n\n if msg.chatId not in self.chatDict:\n self.chatDict[msg.chatId] = chat.Chat(self.g)\n\n self.chatDict[msg.chatId].addMessage(msg)\n\n respMsg = ipcMessage_pb2.Message()\n if msg.respond:\n respMsg.text = self.chatDict[msg.chatId].runNN()\n respMsg.chatId = msg.chatId\n respMsg.userId = msg.userId\n respMsg.time = msg.time\n respMsg.respond = True\n\n conn.send(respMsg.SerializeToString())\n\n\n conn.close()\n\nif __name__ == '__main__':\n Slave(24833)\n","repo_name":"project-galatea/galatea-slave","sub_path":"slave.py","file_name":"slave.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"3600274048","text":"import pandas as pd\nimport re\ndf = pd.read_pickle('processed_tweets.pkl')\n\nurl_re_pattern = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n\ndef text_cleaner(x):\n re.sub(url_re_pattern,'',x)\n split_text = x.split()\n split_text = [w for w in split_text if ('#' not in w) and (w.isalpha())]\n return ' '.join(split_text)\n\ndf['clean_text'] = df['text'].apply(text_cleaner)\n\ndf2 = df.drop_duplicates(subset='clean_text')\n\ndf2['duplicated'] = list(df.groupby(df['clean_text'],as_index=False).size())\n\ndf2.sort_values('duplicated',ascending=False).to_excel('tweet_duplication_scores.xls')\n","repo_name":"Minyall/NoTap_Project_Essex","sub_path":"de_duplicator.py","file_name":"de_duplicator.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"34654634545","text":"\"\"\"empty message\n\nRevision ID: a720f41a6bd4\nRevises: 19a1ca9625e0\nCreate Date: 2022-02-04 15:42:23.032573\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a720f41a6bd4'\ndown_revision = '19a1ca9625e0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('posts', sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True))\n op.add_column('posts', sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('posts', 'updated_at')\n op.drop_column('posts', 'created_at')\n # ### end Alembic commands ###\n","repo_name":"MeiMeiYS/plantstagram","sub_path":"migrations/versions/20220204_154223_.py","file_name":"20220204_154223_.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"7662265416","text":"import cv2\n\n\nimg = cv2.imread(\"lena.jpg\",cv2.IMREAD_COLOR)\nblue, green, red = img[100, 100]\ncv2.imshow('my win',img)\nprint(blue)\nprint(green)\nprint(red)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"JD-edu/aiot-pi","sub_path":"OpenCV_code/401_get_pixel_color.py","file_name":"401_get_pixel_color.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"4750386146","text":"from airflow import DAG\nfrom datetime import datetime, timedelta\nfrom airflow.operators.bash_operator import BashOperator\nfrom textwrap import dedent\n\ndefault_args = {\n 'owner': 'rhuan_lima',\n 'depends_on_past': False,\n 'start_date': datetime(2021, 1, 1),\n 'retries': 0,\n }\n\nwith DAG(\n 'dag-001',\n schedule_interval=timedelta(minutes=1),\n catchup=False,\n default_args=default_args\n ) as dag:\n t1 = BashOperator(\n task_id='print_date',\n bash_command='date',\n )\n t2 = BashOperator(\n task_id='first_etl',\n bash_command=\"\"\"\n cd $AIRFLOW_HOME/dags/etl_scripts/\n python3 py1.py\n \"\"\")\n t3 = BashOperator(\n task_id='second_etl',\n bash_command=\"\"\"\n cd $AIRFLOW_HOME/dags/etl_scripts/\n python3 py2.py\n \"\"\")\n t1.doc_md = dedent(\"\"\"\\\n # Documentação da Task\n Voce pode usar a tag doc_md para passar uma documentação em `Markdow` para o airflow\n\n \"\"\"\n )\n t1 >> t2 >> t3","repo_name":"rhuanlima/AirFlow","sub_path":"dags/dag_001.py","file_name":"dag_001.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"27702644458","text":"def triplets(arr):\n ans = []\n for i in range(len(arr)):\n c = arr[i]\n for j in range(len(arr)):\n if i != j:\n a = arr[j]\n for y in range(j+1, len(arr)):\n if y != i: \n b = arr[y]\n if c**2 - (a**2 + b**2) == 0:\n ans.append([a,b,c])\n\n return ans\n\ndef quicksort(arr):\n if len(arr) < 2:\n return arr\n\n pivot = arr[0]\n less = [i for i in arr[1:] if i <= pivot]\n greater = [i for i in arr[1:] if i > pivot]\n\n return quicksort(less) + [pivot] + quicksort(greater)\n\ndef smart_triplets(arr):\n arr = quicksort(arr)\n ans = []\n for i in range(len(arr)):\n start = 0\n end = len(arr) - 1\n while start < end:\n if i == start:\n start += 1\n elif end == start:\n end -= 1\n\n equ = arr[i]**2 - (arr[start]**2 + arr[end]**2)\n if equ == 0:\n ans.append([arr[start], arr[end], arr[i]])\n start = end\n elif equ < 0:\n end -= 1\n else:\n start += 1\n\n return ans\n \n \n\n return arr\n\nprint(smart_triplets([4,16,1,2,3,5,6,8,25,10]))","repo_name":"tdavchev/algorithms","sub_path":"math and stats/pythagorean_triplets.py","file_name":"pythagorean_triplets.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"18793878249","text":"from mpi4py import MPI \n\ncomm=MPI.COMM_WORLD\nrank=comm.Get_rank()\nsendmsg=rank\n\nprint(\"I am rank {} I have sendmsg as {}\".format(rank,sendmsg))\nrecvmsg1=comm.reduce(sendmsg,op=MPI.SUM,root=0)\n\nif rank==0:\n print(\"rank zero\",recvmsg1)\n\nprint(\"all reduce at rank {}\".format(rank))\nrecvmsg2=comm.allreduce(sendmsg,op=MPI.SUM)\nprint(\"I am rank {} I have recvmsg2 op=MPI.SUM as {}\".format(rank,recvmsg2))","repo_name":"terasakisatoshi/HPC","sub_path":"PythonMPI/reduceall.py","file_name":"reduceall.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"74324945539","text":"#!/usr/bin/env python3\n\nimport csv\nimport matplotlib.pyplot as plt\nimport json\n\nkoibs = json.loads(open(\"koibs_kegs.json\").read())\nsKoibs = set()\nfor k, v in koibs.items():\n for koib in v[\"koibs\"]:\n sKoibs.add(k + str(koib))\nprint(\"#Koibs: %d\" % len(sKoibs))\n\nputinBins = [0]*101\nnonPutinKoibBins = [0]*101\nputinKoibBins = [0]*101\nputinCrimeaBins = [0]*101\nputinCrimeaKoibBins = [0]*101\nregionTurnout = {}\nvotes90 = 0\nwith open(\"table_227_level_3.tsv\", \"r\") as f:\n next(f)\n for line in f:\n row = line.strip().split(\"\\t\")\n total = int(row[3])\n votes = int(row[12])\n putin = int(row[18])\n region = row[0]\n number = int(row[2][5:])\n # print(total, votes, putin)\n assert votes <= total\n assert putin <= votes\n if votes:\n turnoutPair = (votes, total)\n\n turnout = float(votes)/total\n putinRatio = float(putin)/float(votes)\n putinBin = int(100.0 * putinRatio)\n if region + str(number) in sKoibs:\n if (putinBin > 89) and (putinBin <= 95) and (turnout < 0.65):\n print(region, number, putin)\n if region in regionTurnout:\n regionTurnout[region] = (regionTurnout[region][0] + turnoutPair[0], regionTurnout[region][1] + turnoutPair[1])\n else:\n regionTurnout[region] = turnoutPair\n votes90 += votes\n\n putinKoibBins[putinBin] += 3*putin\n nonPutinKoibBins[putinBin] += 3*(votes - putin)\n else:\n putinBins[putinBin] += putin\n if region == \"Республика Крым\":\n if region + str(number) in sKoibs:\n putinCrimeaKoibBins[putinBin] += 15*putin\n else:\n putinCrimeaBins[putinBin] += putin\n\nfor r, pair in regionTurnout.items():\n print(\"%s\\t%f\\t%d\\t%f\" % (r, pair[0]/pair[1], pair[0], float(pair[0])/votes90))\n\nabins = []\nfor i in range(101):\n abins.append(i)\n\nplt.clf()\nplt.plot(abins, putinBins, color='red', label=\"Putin (KOIB only)\")\nplt.plot(abins, nonPutinKoibBins, color='blue', label=\"Others (KOIB only)\")\nplt.xlabel(\"Putin's votes share\")\nplt.ylabel(\"Sum of #votes\")\nplt.legend()\nplt.suptitle(\"Russia\")\nplt.savefig(\"pOthers.png\", dpi=300)\nplt.show()\n\nplt.clf()\nplt.plot(abins, putinBins, color='red', label=\"Putin without KOIB\")\nplt.plot(abins, putinKoibBins, color='blue', label=\"Putin with KOIB * 3\")\nplt.xlabel(\"Putin's votes share\")\nplt.ylabel(\"Sum of #votes\")\nplt.legend()\nplt.suptitle(\"Russia\")\nplt.savefig(\"pAll.png\", dpi=300)\nplt.show()\n\nplt.clf()\nplt.plot(abins, putinCrimeaBins, color='red', label=\"Putin without KOIB\")\nplt.plot(abins, putinCrimeaKoibBins, color='blue', label=\"Putin with KOIB * 15\")\nplt.xlabel(\"Putin's votes share\")\nplt.ylabel(\"Sum of #votes\")\nplt.legend()\nplt.suptitle(\"Crimea\")\nplt.savefig(\"pCrimea.png\", dpi=300)\nplt.show()\n","repo_name":"evilmucedin/ukraineElection2019","sub_path":"russia2018/hist.py","file_name":"hist.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"36309283225","text":"from ..common.basetrackservice import BaseTrackService, track_registry\nimport requests\nfrom ..models.model import StatusChoice\nimport parsel\nfrom dateutil.parser import parse\n\n\ndef get_elem_text(el):\n sentence = \"\"\n if el:\n for word in el:\n s_word = word.strip()\n sentence += s_word + \" \"\n return sentence.strip()\n\n\n@track_registry.register(\"firstmile\")\nclass FirstMile(BaseTrackService):\n def status_mapper(self, status):\n \"\"\"\n docstring\n \"\"\"\n if status.startswith(\"Shipment info received\"):\n return StatusChoice.InfoReceived.value\n elif status.startswith(\"Picked Up\"):\n return StatusChoice.InTransit.value\n elif status.startswith(\"Departed\"):\n return StatusChoice.InTransit.value\n elif status.startswith(\"Accepted\"):\n return StatusChoice.InTransit.value\n elif status.startswith(\"Arrived\"):\n return StatusChoice.InTransit.value\n elif status.startswith(\"Out for Delivery\"):\n return StatusChoice.OutForDelivery.value\n elif status.startswith(\"Delivered\"):\n return StatusChoice.Delivered.value\n elif \"Delivered\" in status:\n return StatusChoice.Delivered.value\n else:\n return \"Exception\"\n\n def __init__(self, waybill, *args, **kwargs):\n super().__init__(waybill, \"firstmile\", *args, **kwargs)\n\n \"\"\"\n This method will populate self.raw_data\n \"\"\"\n\n def _fetch(self):\n self.raw_data = requests.post(\n f\"https://track.firstmile.com/detail.php?n={self.waybill}&tz=Asia/Calcutta\",\n verify=False,\n ).text\n # print(self.raw_data, \"####\")\n\n \"\"\"\n This method will convert self.raw_data to self.data\n \"\"\"\n\n def _transform(self):\n selector = parsel.Selector(text=self.raw_data)\n sub_status = selector.xpath(\n '//*[@id=\"packageDetail\"]/div/article/section[1]/section/div/h2/text()'\n ).get()\n sub_status = sub_status.strip() if sub_status else \"\"\n status = self.status_mapper(sub_status)\n delivered_date = None\n if status == \"Delivered\":\n delivered_date = selector.xpath(\n '//*[@id=\"packageDetail\"]/div/article/section[1]/section/div/h4/text()'\n ).get()\n\n data = {\n \"waybill\": self.waybill,\n \"provider\": self.provider,\n \"status\": status,\n \"substatus\": sub_status,\n \"estimated_date\": None,\n \"delivered_date\": delivered_date,\n \"delivered_time\": \"\",\n \"reference_no\": \"\",\n \"destination\": \"\",\n \"receiver_name\": \"\",\n }\n\n checkpoint_section = selector.css(\".historyWrap>div\")\n\n checkpoints = []\n current_date = None\n\n for row in checkpoint_section:\n if \"dateRow\" in row.attrib[\"class\"]:\n current_date = row.xpath(\"./text()\").get()\n continue\n\n checkpoint_time = parse(current_date + row.css(\".date::text\").get())\n message = get_elem_text(row.css(\".info *::text\").getall())\n location = get_elem_text(row.css(\".location *::text\").getall())\n\n checkpoint = {\n \"slug\": self.provider,\n \"location\": location,\n \"country_name\": \"\",\n \"message\": message,\n \"submessage\": message,\n \"country_iso3\": \"\",\n \"status\": self.status_mapper(message),\n \"substatus\": message,\n \"checkpoint_time\": checkpoint_time,\n \"state\": None,\n \"zip\": None,\n }\n checkpoints.append(checkpoint)\n\n data[\"checkpoints\"] = checkpoints\n self.data = data\n","repo_name":"ShipKore/libshipkore","sub_path":"libshipkore/track/tracker/firstmile.py","file_name":"firstmile.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"80"} +{"seq_id":"40517750565","text":"import tkinter as tk\nfrom tkinter import *\nfrom tkinter import messagebox ##messageboxes\nimport musicpd #http://www.musicpd.org/doc/protocol/\nimport paramiko\nfrom paramiko import * #for ssh\n\n##managing the connection:\nclass connectobject(object):\n\tdef __init__(self, arg1, arg2, arg3):##initialization. takes URL, port and username for ssh\n\t\tself.arg1 = arg1 \n\t\tself.arg2 = arg2\n\t\tself.arg3 = arg3\n\tdef connect(self):##connects to server\n\t\ttry:\n\t\t\tclient.connect(self.arg1, self.arg2) \n\t\texcept musicpd.ConnectionError:\n\t\t\tpass\n\tdef print(self):\n\t\tresult = \"Server: \" + self.arg1 + \"\\n Port: \" + str(self.arg2) + \"\\nUsername: \" + str(self.arg3)##save info to string and give it back\n\t\treturn(result)\n\tdef disconnect(self):#disconnect from server\n\t\ttry:\n\t\t\tclient.close()\t\t # send the close command\n\t\t\tclient.disconnect()\n\t\texcept musicpd.ConnectionError: #if it is not connected, do nothing. prevents the whole thing from shutting down\n\t\t\tpass\n\tdef change(self, arg1, arg2, arg3):#changes the IP and Port\n\t\tself.arg1 = arg1\n\t\tself.arg2 = arg2\n\t\tself.arg3 = arg3\n\tdef safe(self):####save actual configuration to config-file\n\t\tconfigfile = open(\"config.txt\", 'w') ##open in read-mode then delete the contents and write down Server and IP\n\t\tconfigfile.truncate()\n\t\ttextstring = connectinfo.arg1\n\t\tuserstring = connectinfo.arg3\n\t\tportconfig = str(connectinfo.arg2)\n\t\tconfigfile.write(portconfig)\n\t\tconfigfile.write(\"\\n\")\n\t\tconfigfile.write(textstring)\n\t\tconfigfile.write(\"\\n\")\n\t\tconfigfile.write(userstring)\n\t\tconfigfile.close()\t\n\t\tmaster.quit()##exits program\n\tdef getip(self): #gives back IP\n\t\tresult = self.arg1\n\t\treturn result\n\tdef getport(self): #gives back Port\n\t\tresult = int(self.arg2)\n\t\treturn result\n\tdef getuser(self): #gives back User\n\t\tresult = self.arg3\n\t\treturn result\n\t\n\n\ndef secondstominutes(secondsinput):##converts seconds to minutes\n\tif (secondsinput > 3600): ##write playlist in hours, if it is longer than one hour\n\t\thours = int(secondsinput/3600)\n\t\tminutes = round(int(secondsinput % 3600)/60)\n\t\tseconds = round(minutes % 60)\n\t\treturnstring = str(hours) + \":\" + str(minutes) + \":\" + str(seconds)\n\telse:#write playlist in minutes, if it is shorter than an hour\n\t\tseconds = round(secondsinput % 60)\n\t\tminutes = int(secondsinput /60)\n\t\treturnstring = str(minutes) + \":\" + str(seconds)\n\treturn(returnstring)\n\n####draw some windows\ndef drawscrollbar():##shows actual playlist (currently not updating, so you have to re-open it all the time)\n\tmaster2 = tk.Tk()\n\tb1 = Button(master2,text=\"Play Track\",command=playselectedtitle).pack()\n\tb2 = Button(master2,text=\"Remove Track\",command=deleteselectedtitle).pack()\n\tconnectinfo.connect()\n\tscrollbar = Scrollbar(master2)\n\tscrollbar.pack(side=RIGHT, fill=Y)\n\tglobal listbox2\n\tlistbox2 = Listbox(master2, yscrollcommand=scrollbar.set)\n\ttext = drawplaylist()\n\tmaster2.title(text)\n\tlistbox2.pack(side=LEFT, fill=BOTH, expand=50)\n\tscrollbar.config(command=listbox2.yview)\n\tconnectinfo.disconnect()\n\t\ndef drawplaylist(): #draws playlist to update the view.\n\tsecondstotal = 0\n\ti=0\n\tconnectinfo.connect()\n\tfor song in client.playlistinfo():\n\t\tsecondstotal = float(song['time']) + secondstotal\n\t\tsongtime = secondstominutes(float(song['time']))\n\t\ttext9 = song['pos'] + \" \" + song['artist'] + \" - \" + song['title'] +\" \" + songtime\n\t\tlistbox2.insert(END, text9) \n\t\ti+=1 \n\ttotaltime = secondstominutes(secondstotal)\n\ttext = \"Actual Playlist | Total time: \" + totaltime + \" | \" + str(i) + \" Songs\"\n\tconnectinfo.disconnect()\n\treturn text\n\ndef playselectedtitle():##plays selected sond of the playlist\n tracknumber = min(listbox2.curselection()) \n connectinfo.connect()\n client.play(tracknumber)\n connectinfo.disconnect()\n\ndef deleteselectedtitle():##removes selected track from playlist (not properly working)\n tracknumber = min(listbox2.curselection()) \n connectinfo.connect()\n #client.deleteid(tracknumber)\n client.delete(tracknumber)\n #print(tracknumber)\n #test() --> should call function drawplaylist, to update the playlist, but not working\n connectinfo.disconnect()\n\ndef drawallplaylists():##list all playlists\n\tconnectinfo.connect()\n\tmaster3 = tk.Tk()\n\tmaster3.title(\"Playlist overview\")\n\tmaster3.minsize(width=50, height=300) #makes that the window is not shown too small, but not a very nice solution\n\tb1 = Button(master3,text=\"Add playlist\",command=addEntry).pack(side = LEFT)\n\tscrollbar = Scrollbar(master3)\n\tscrollbar.pack(side=RIGHT, fill=Y)\n\tglobal listbox\n\tlistbox = Listbox(master3, yscrollcommand=scrollbar.set)\t\n\tclient.iterate = True\n\ti = 0\n\tfor song in client.listplaylists():\n\t\ttext9 = str(i) + \" \"+ song['playlist']\n\t\ti = i+1\n\t\tlistbox.insert(END, text9) \n\tlistbox.pack(side=LEFT, fill=BOTH, expand=50)\n\tscrollbar.config(command=listbox.yview)\n\tconnectinfo.disconnect()\n\t\n\ndef addEntry():##adds selected playlist to the playlist\n playlistnumber = min(listbox.curselection()) ##get selection of listbox\n connectinfo.connect() \n i = 0\n j = []\n for song in client.listplaylists():\n j.append(song['playlist'])#creating an array so you can access the name of the playlist. Needed because otherwise you get an error\n i+=1\n\t#add playlist by number:\n client.load(j[playlistnumber])#call this entry in the list and load the playlist\n connectinfo.disconnect()\n\n\ndef displaysong(label):##shows the actual song, time played and so on. updates every second\n\tdef display():\n\t\tconnectinfo.connect()\n\t\ttry:\n\t\t\ttimeplayed = secondstominutes(float(client.status()['elapsed']))\n\t\t\ttimesong = secondstominutes(float(client.currentsong()['time']))\n\t\t\ttext = client.currentsong()['artist'] + \" - \" + client.currentsong()['title'] + \" | \" + timeplayed + \"/\" + timesong + \"\\n\" + \"Album: \" + client.currentsong()['album'] + \" | Songnumber: \" + client.status()['song'] + \"\\n\" + client.status()['state'] + \" \" + \"random: \" + client.status()['random'] + \" | repeat: \" + client.status()['repeat'] + \" \\n\" +\"consume: \" + client.status()['consume'] + \" | single: \" + client.status()['single']\n\t\t\tvolume = w2.get() ##sets volume based on the slider at the right. Because of the exception it only does this when a song is playing\n\t\t\tclient.setvol(volume)\n\t\texcept KeyError: ##if no songs are loaded in the playlist, it will produce a key error. If this occurs, it says no song playing\n\t\t\ttext = \"no song playing\"\t\t\t\n\t\texcept musicpd.ConnectionError:\n\t\t\ttext = \"not connected or wrong IP/Port\"\n\t\tlabel.config(text=text, justify=LEFT)\n\t\tlabel.after(1000, display)\n\t\tconnectinfo.disconnect()\n\tdisplay()\n\ndef about(): ##draw window 'about'\n\tmaster5 = tk.Tk()\n\tmaster5.title('About')\n\tlabel = tk.Label(master5)\n\ttext = \"This program was written by Julian Hocker, licenced under the GPL\"\n\ttext = text + \"\\n\" + connectinfo.print()\n\tlabel.config(text =text)\n\tlabel.grid()\n\t\n\t\n\t\n#############manipulate playback\ndef setpause():\n connectinfo.connect()\n client.pause()\n connectinfo.disconnect()\n\ndef playnext(): ##play next track\n connectinfo.connect()\n client.next()\n connectinfo.disconnect()\n\nclass playattributes():##bundles all functions for playing like random, single, consume, repeat and clearplaylist\n\tdef random():#toggle random\n\t\tconnectinfo.connect()\n\t\tif (client.status()['random'] == \"1\"):\n\t\t\tclient.random(0)\n\t\telse:\n\t\t\tclient.random(1)\n\t\tconnectinfo.disconnect()\n\t\n\tdef single():#toggle single (only current song is played until the end)\n\t\tconnectinfo.connect()\n\t\tif (client.status()['single'] == \"1\"):\n\t\t\tclient.single(0)\n\t\telse:\n\t\t\tclient.single(1)\n\t\tconnectinfo.disconnect()\n\t\t\n\tdef consume():#toggle consume (each played song is removed from playlist)\n\t\tconnectinfo.connect()\n\t\tif (client.status()['consume'] == \"1\"):\n\t\t\tclient.consume(0)\n\t\telse:\n\t\t\tclient.consume(1)\n\t\tconnectinfo.disconnect()\n\t\t\n\tdef repeat():#toggle repeat\n\t\tconnectinfo.connect()\n\t\tif (client.status()['repeat'] == \"1\"):\n\t\t\tclient.repeat(0)\n\t\telse:\n\t\t\tclient.repeat(1)\n\t\tconnectinfo.disconnect()\n\t\n\tdef clearplaylist(): #clear the playlist\n\t connectinfo.connect()\n\t client.clear()\n\t connectinfo.disconnect()\n\t\ndef playlast():##start current track again or play song before if actual song runs less than 10 seconds\n connectinfo.connect() \n tracknumber = float(client.status()['song'])\n tracknumber = int(tracknumber)\t\n if (float(client.status()['elapsed'])<10):\n tracknumber = tracknumber -1\n else:\n pass\t\n client.play(tracknumber)\n connectinfo.disconnect()\n\n\n\n####window 'add'\ndef addurl():##adds an URL (currently only mp3/ogg-streams, no youtube). Youtube-code: \"yt:https://www.youtube.com/watch?v=N9nUIFYc5II\" but also on server not working :(\n connectinfo.connect()\n url = e3.get()\n try:\n client.add(url)\n except musicpd.CommandError:\n messagebox.showwarning(\"Error\", \"Please enter a playable URL\")\n connectinfo.disconnect()\n e3.delete(0,END)\n\n\ndef addstuff():##main window for adding URLs, Playlist and play a tracknumber (not very nice grouped)\n\tmaster4 = tk.Tk()\n\tmaster4.title(\"Add URL\")\n\t##Add an URL\n\tglobal e3 \n\te3= Entry(master4)\n\te3.grid(row=2, column=0)\n\tButton(master4, text='Add URL', command=addurl).grid(row=2, column=1)\n\t\ndef addlocal():##main window for adding an album on the local hard disc\n\tmaster5 = tk.Tk()\n\tmaster5.title(\"Adding\")\n\tlabel = tk.Label(master5, text=\"Artist:\",justify = LEFT)\n\tlabel.grid(row = 0, column= 0)\n\tglobal e5\n\te5= Entry(master5)\n\te5.grid(row = 0, column= 1)\n\tglobal e6\n\te6= Entry(master5)\n\te6.grid(row = 1, column= 1)\n\tlabel = tk.Label(master5, text=\"Album:\",justify = LEFT)\n\tlabel.grid(row = 1, column= 0)\n\tButton(master5, text='Add Album', command=addlocalfiles).grid(row = 2, column= 0)\n\tButton(master5, text='Show Albums of Artist', command=showalbums).grid(row = 2, column= 1)\n\tglobal labellocalartists\n\tlabellocalartists = tk.Label(master5, justify = LEFT)\n\tlabellocalartists.grid(row = 0, column= 3, rowspan = 3)\n\n\ndef addlocalfiles():#adds album according to artist and album name\n\tartist = e5.get()\n\talbum = e6.get()\t\n\tinput = \"Local media/Artists/\" + artist + \"/\" + album\n\tconnectinfo.connect()\n\tfor song in client.lsinfo(input):\n\t\ttext10 = song['file']\n\t\tclient.add(text10)\n\tconnectinfo.disconnect()\n\te5.delete(0,END)\n\te6.delete(0,END)\n\ndef showalbums():\n\tinput = \"Local media/Artists/\" + e5.get()\n\tstringlength = len(input) +1\n\ttext9 = \"\"\n\tconnectinfo.connect()\n\tfor song in client.lsinfo(input):\n\t\ttext9 = text9 + song['directory'][stringlength:] + \"\\n\"\n\tlabellocalartists.config(text=text9)\n\tconnectinfo.disconnect()\n\n####class for setting up the server\nclass serversetup():\n\tdef serversetupwindow():#window for serversetup\n\t\tserversetupwin = tk.Tk()\n\t\tserversetupwin.title(\"Set up IP and Port\")\n\t\tlabel = tk.Label(serversetupwin, text=\"IP:\",justify = LEFT)\n\t\tlabel.grid(row = 0, column= 0)\n\t\tlabel = tk.Label(serversetupwin, text=\"Port:\",justify = LEFT)\n\t\tlabel.grid(row = 1, column= 0)\n\t\tlabel = tk.Label(serversetupwin, text=\"Username:\",justify = LEFT)\n\t\tlabel.grid(row = 2, column= 0)\n\t\tglobal e7\n\t\te7= Entry(serversetupwin)\n\t\te7.grid(row = 0, column= 1)\n\t\tglobal e8\n\t\te8= Entry(serversetupwin)\n\t\te8.grid(row = 1, column= 1)\n\t\tglobal e20\n\t\te20= Entry(serversetupwin)\n\t\te20.grid(row = 2, column= 1)\t\t\n\t\tButton(serversetupwin, text='Update IP and Port', command=serversetup.serversetupbutton).grid(row = 3, column= 1)\n\n\tdef serversetupbutton():#changes connection info based on input at serversetup\n\t\tip = e7.get()\n\t\tport = int(e8.get())\n\t\tuser = e20.get()\n\t\tconnectinfo.change(ip, port,user)\n\t\te7.delete(0,END)\n\t\te8.delete(0,END)\n\t\te20.delete(0,END)\n\t\n##class that connects to the server via ssh and can shut down the server\nclass shutdown():\n\tdef sshshutdown():\n\t\tsshclient = SSHClient() ##init sshclient\n\t\tsshclient.load_system_host_keys()\n\t\tpassword = sshpasswordinput.get()\n\t\ttry:\n\t\t\tsshclient.connect(connectinfo.getip(), username = connectinfo.getuser(), password = password) \n\t\t\ttime = sshtimeinput.get()\n\t\t\tcommand = 'sudo shutdown -hP ' + time #shutdown with given time\n\t\t\tsshclient.exec_command(command)\n\t\t\tsshclient.close()\n\t\texcept paramiko.ssh_exception.AuthenticationException:\n\t\t\tmessagebox.showwarning(\"Error\", \"Wrong username or password\")\n\t\tsshpasswordinput.delete(0,END) #delete field with password\n\t\tsshtimeinput.delete(0,END) #delete field with time\n\n\tdef mainwindow(): #main window, you have to provide the time and the passoword for the server\n\t\tshutdownwindow = tk.Tk()\n\t\tshutdownwindow.title(\"MPC Shutdown\")#title\n\t\tshutdownwindow.minsize(width=150, height=100)##minimum size\n\t\tlabel = tk.Label(shutdownwindow, justify = LEFT, text=\"Enter Passwort\")\n\t\tlabel.grid(column=0, row= 0)\n\t\tlabel2 = tk.Label(shutdownwindow, justify = LEFT, text=\"Enter Time \")\n\t\tlabel2.grid(column=0, row= 1)\n\t\tglobal sshpasswordinput\n\t\tsshpasswordinput= Entry(shutdownwindow, show=\"*\")##make password invisible, input field for password\n\t\tsshpasswordinput.grid(row = 0, column= 1)\n\t\tglobal sshtimeinput\n\t\tsshtimeinput= Entry(shutdownwindow)#entry-field for time\n\t\tsshtimeinput.grid(row = 1, column= 1)\n\t\tbutton1 = tk.Button(shutdownwindow, text='Shutdown', width=10, command=shutdown.sshshutdown)\n\t\tbutton1.grid(column=1, row= 2)\t\n\t\n\t\n####setting up connection\ntry:\n\twith open('config.txt') as f:#open file\n\t\tlines = f.readlines()\n\tIP = lines[1]#IP is line number 2\n\tIP = IP[:-1]#get rid of linbreak after ip\n\tUSER = lines[2]#USER is line number 3\n\tPORT = int(lines[0]) #Port is line number 1\n\tf.close()\nexcept FileNotFoundError:#if it cannot find the file, set IP and Port to a random value so program starts and user can change it\n\tIP = '192.168.1.2'\n\tPORT = 6600\n\tUSER = 'root'\nexcept ValueError:#if file is corrupted, set IP and Port to a random value so program starts and user can change it\n\tIP = '192.168.1.2'\n\tPORT = 6600\n\tUSER = 'root'\nexcept IndexError:#if file is corrupted, set IP and Port to a random value so program starts and user can change it\n\tIP = '192.168.1.2'\n\tPORT = 6600\n\tUSER = 'root'\n\nclient = musicpd.MPDClient()#set up basic object for MPD-Client\nconnectinfo = connectobject(IP, PORT, USER)#set object with connection settings\n\n\n#####################\n##########main window\nmaster = tk.Tk()\nmaster.title(\"MPC Control\")#title\nmaster.minsize(width=150, height=100)##minimum size\n\nlabel = tk.Label(master, justify = LEFT)\nlabel.grid(column=0, row= 0, columnspan = 3)\nw2 = Scale(master, from_=100, to=0)\nw2.set(100)\nw2.grid(column=3, row= 0, rowspan = 2)\ndisplaysong(label)##label for actual song\n\n#buttons for controlling the playback\nbutton1 = tk.Button(master, text='<<', width=10, command=playlast)\nbutton1.grid(column=0, row= 1)\nbutton2 = tk.Button(master, text='||', width=10, command=setpause)\nbutton2.grid(column=1, row= 1)\nbutton3 = tk.Button(master, text='>>', width=10, command=playnext)\nbutton3.grid(column=2, row= 1)\n\n\n\n####Menu\nmenu = Menu(master)\nmaster.config(menu=menu)\nfilemenu = Menu(menu)\nmenu.add_cascade(label=\"File\", menu=filemenu)\nfilemenu.add_command(label=\"Playlist\", command=drawscrollbar)\nfilemenu.add_command(label=\"All playlists\", command=drawallplaylists)\nfilemenu.add_command(label=\"Add URL\", command=addstuff)\nfilemenu.add_command(label=\"Add Local files\", command=addlocal)\nfilemenu.add_command(label=\"Exit\", command=connectinfo.safe) ###should save the actual server configuration to file and read it when it starts\n\nmenu2 = Menu(master)\nmaster.config(menu=menu)\nnewmenu = Menu(menu2)\nmenu.add_cascade(label=\"Playback modes\", menu=newmenu)\nnewmenu.add_command(label=\"Clear Playlist\", command=playattributes.clearplaylist)\nnewmenu.add_command(label=\"Toggle Random\", command=playattributes.random)\nnewmenu.add_command(label=\"Toggle Repeat\", command=playattributes.repeat)\nnewmenu.add_command(label=\"Toggle consume\", command=playattributes.consume)\nnewmenu.add_command(label=\"Toggle single\", command=playattributes.single)\n\nmenu3 = Menu(master)\nmaster.config(menu=menu)\nnewmenu = Menu(menu3)\nmenu.add_cascade(label=\"About/setup\", menu=newmenu)\nnewmenu.add_command(label=\"Set up Server\", command=serversetup.serversetupwindow)\nnewmenu.add_command(label=\"About\", command=about)\nnewmenu.add_command(label=\"Shutdown\", command=shutdown.mainwindow)\n\n##############\nmaster.protocol(\"WM_DELETE_WINDOW\", connectinfo.safe)\nmainloop()\n","repo_name":"masterofpuppets103/mpd","sub_path":"mpdcontrol_gui.py","file_name":"mpdcontrol_gui.py","file_ext":"py","file_size_in_byte":16144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"40864577738","text":"\n# https://atcoder.jp/contests/dp/tasks/dp_c \n\n# Days\nN = 3\npoints=[\n[10, 40, 70],\n[20, 50, 80],\n[30, 60, 90]\n]\n\ndef max_points():\n DP=[[0]*N for i in range(3)]\n for d in range(N):#days\n if d ==0:\n for a in range(3):\n DP[d][a] = points[d][a]\n continue\n for a in range(3):#activities\n for b in range(3):#activities\n if a != b:\n DP[d][b]=max(DP[d][b],DP[d-1][a]+points[d][b])\n print(DP)\n return DP[N-1][2]\n\nprint(max_points())","repo_name":"andresesfm/coding_challenges","sub_path":"atcoder.jp/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"37853254454","text":"import urllib.request\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef scapLinkedIn(url):\r\n\turlopener= urllib.request.build_opener()\r\n\turlopener.addheaders = [('User-agent', 'Mozilla/5.0')]\r\n\tpage= urlopener.open(url).read()\r\n\t#print(page)\r\n\t\r\n\tdata = str(page)\r\n\tsoup = BeautifulSoup(data)\r\n\tprofile = soup.find_all(\"div\", { \"id\" : \"profile\" })\r\n\tprint(profile)\r\n\t\r\n\t'''response = urllib.request.urlopen(url)\r\n\tpage = response.read()'''\r\n\t\r\n\thtml = str(page)\r\n\tstart = html.find('
')\r\n\t#print (start)\r\n\tend = html.find('
')\r\n\tuser_data = html[start:end]\r\n\t#print(user_data)\r\n\tfo = open(url+\".html\", \"wb\")\r\n\tfo.write(page);\r\n\tfo = open(url+\".html\", \"wb\")\r\n\tfo.write((str(profile)).encode('utf8'));\r\n\r\nscapLinkedIn(\"https://www.linkedin.com/in/kishankathiriya/\")\r\n#scapLinkedIn(\"https://www.google.com\")","repo_name":"tc18/TkScrapper","sub_path":"scapper.py","file_name":"scapper.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"71086746820","text":"from rest_framework import serializers\nfrom .models import Todo\nclass TodoSerializer(serializers.ModelSerializer):\n class Meta:\n model=Todo\n fields=( \n 'id', #! (__all__) butun field lerin gelmesini istersek.\n 'task',\n 'description',\n 'priority',\n 'is_done',\n 'created_date'\n )","repo_name":"iamfatihay/Django","sub_path":"class-notes/09_Task_Tracker/todoApp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"22191439622","text":"import sys\r\n\r\nsys.stdin = open('input.txt')\r\n\r\ninput = sys.stdin.readline\r\n\r\n# 여기부터 백준 코드 입력\r\n\r\nM = int(input())\r\nN = int(input())\r\nsum = 0\r\n\r\nfor i in range(N):\r\n a,b = map(int, input().split())\r\n sum += a*b\r\n \r\nif sum == M:\r\n print(\"Yes\")\r\nelif sum != M:\r\n print(\"No\") ","repo_name":"ohiju/Algorithm_Study","sub_path":"baekjoon/3. 반복문/25304.py","file_name":"25304.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39147859996","text":"# -*- coding: utf-8 -*-\n\nimport streamlit as st\nimport pandas as pd\nimport time, re\nimport wikipedia\n\nfrom multiprocessing import freeze_support\n\nfrom cdqa.utils.download import download_model\nfrom cdqa.pipeline.cdqa_sklearn import QAPipeline\n\nHTML_WRAPPER = \"\"\"{}\"\"\"\n\nif __name__ == '__main__':\n freeze_support()\n\n st.title('Un démonstrateur pour PIAF')\n st.write(\"Ceci est un démonstrateur du potentiel d'un système de Question Answering, ici en anglais.\\\n Posez vos questions sur un paragraphe de texte et admirez le résultat ! \\N{bird}\")\n \n langu = st.sidebar.selectbox(\"Langue\", [\"Français\", \"Anglais\"])\n # mod = st.sidebar.selectbox(\"Modèle\", [\"Bert SQuAD 1.1\", \"Bert SQuAD 2.0\"])\n source = st.sidebar.selectbox(\"Source\", [\"Le RGPD\", \"Un article Wikipédia au choix\", \"Un paragraphe de votre cru\"])\n \n if \"Wikipédia\" in source:\n \n if \"Français\" in langu:\n wikipedia.set_lang(\"fr\")\n pagename = st.sidebar.text_area(\"Nom de l'article\", 'Élisabeth II')\n else:\n wikipedia.set_lang(\"en\")\n pagename = st.sidebar.text_area(\"Nom de l'article\", 'Elizabeth II')\n \n title, id, paragraphs = [], [], []\n page = wikipedia.page(pagename)\n title.append(page.title)\n id.append(page.pageid)\n content = re.split('\\n{1,3}={2,3}\\s.+\\s={2,3}\\n{1,2}|\\n', page.content)\n paragraphs.append([s for s in content if s != ''])\n \n df = pd.DataFrame({'id': id, 'title': title, 'paragraphs': paragraphs})\n \n if \"Français\" in langu:\n default_query = \"Qu'est ce que {} ?\".format(page.title)\n else:\n default_query = 'What is {}?'.format(page.title)\n \n st.header('Posez vos questions sur l\\'article : {}'.format(page.title))\n st.write(\"Introduction : *{}*\".format(df.loc[0,'paragraphs'][0]))\n \n elif 'RGPD' in source:\n \n default_query = \"Who can access my personal data?\"\n pattern = re.compile('Article\\s\\d{1,2}\\.*')\n f = open(\"data/GDPR.txt\", \"r\", encoding='utf-8')\n content = f.read().split('\\n\\n')\n content = [c for c in content if pattern.match(c)]\n df = pd.DataFrame([[0, 'RGPD', content]], columns=['id', 'title', 'paragraphs'])\n \n else:\n \n if \"Français\" in langu:\n default = \"Le recours à l’intelligence artificielle au sein de l’action publique est souvent identifié comme une opportunité pour interroger des textes documentaires et réaliser des outils de questions/réponses automatiques à destination des usagers. Interroger le code du travail en langage naturel, mettre à disposition un agent conversationnel pour un service donné, développer des moteurs de recherche performants, améliorer la gestion des connaissances, autant d’activités qui nécessitent de disposer de corpus de données d’entraînement de qualité afin de développer des algorithmes de questions/réponses. Aujourd’hui, il n’existe pas de jeux de données d’entraînement francophones publics et ouverts qui permettrait d’entraîner ces algorithmes. L’ambition du projet PIAF est de construire ce(s) jeu(x) de données francophones pour l’IA de manière ouverte et contributive\"\n default_query = 'Quel est le but de PIAF ?'\n else:\n default = \"The use of artificial intelligence in public action is often identified as an opportunity to interrogate documentary texts and to create automatic question / answer tools for users. Querying natural language work code, providing a conversational agent for a given service, developing high-performance search engines, improving knowledge management, all activities that require quality training data corpus to develop question and answer algorithms. Today, there are no public and open French training data sets that would train these algorithms. The ambition of the PIAF project is to build this set of Francophone data for AI in an open and contributive way.\"\n default_query = 'What is the aim of PIAF?'\n \n para = st.text_area('Ecrivez ici le paragraphe source', default)\n df = pd.DataFrame([[0, 'My paragraph', [para]]], columns=['id', 'title', 'paragraphs'])\n \n \n ### MODEL TRAINING SECTION ###\n \n s1 = time.time()\n\n if not \"Français\" in langu:\n download_model(model='bert-squad_1.1', dir='./models')\n cdqa_pipeline = QAPipeline(reader='models/bert_qa.joblib', max_df=1.0, min_df=1)\n else:\n cdqa_pipeline = QAPipeline(reader='models/bert_qa_fr.joblib', max_df=1.0, min_df=1)\n \n # cdqa_pipeline.cuda()\n t1 = time.time() - s1\n\n s2 = time.time()\n # Fitting the retriever to the list of documents in the dataframe\n cdqa_pipeline.fit_retriever(df)\n t2 = time.time() - s2\n\n # Querying and displaying\n query = st.text_area('Posez votre question ici !', default_query)\n \n s3 = time.time()\n prediction = cdqa_pipeline.predict(query)\n t3 = time.time() - s3\n \n st.header('Réponse : {}\\n'.format(prediction[0]))\n # st.write('Article d\\'où la réponse est extraite : *{}*\\n'.format(prediction[1]))\n res = prediction[2].replace(prediction[0], HTML_WRAPPER.format(prediction[0]))\n if \"Wikipédia\" in source:\n st.write('Paragraphe de l\\'article : *{}*\\n'.format(res), unsafe_allow_html=True)\n elif \"RGPD\" in source:\n st.write('Article concerné : *{}*\\n'.format(res), unsafe_allow_html=True)\n else:\n st.write('Localisation de la réponse : *{}*\\n'.format(res), unsafe_allow_html=True)\n \n st.write('Répondre à votre question a nécessité ', round(t3), ' secondes, charger le modèle', round(t1), 'secondes.')\n \n","repo_name":"etalab-ia/demo-piaf","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":6134,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"36296365847","text":"import re\nimport csv\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.probability import FreqDist\nfrom nltk import ngrams\nfrom nltk.corpus import movie_reviews\nfrom collections import Counter\n\nbigramsDictionary = Counter()\nunigramsDictionary = Counter()\nbigramsProbability = {}\n\nall_words = []\nfor w in movie_reviews.words():\n\tall_words.append(w.lower())\n\nnew_words = []\nfor w in all_words:\n\tif w.isalpha():\n\t\tnew_words.append(w)\n\nstopWords = set(stopwords.words(\"english\"))\ncharacter = {'u'}\ntokensFiltered = []\n\nfor token in new_words:\n\tif token not in stopWords:\n\t\ttokensFiltered.append(token)\n\n\nunigramsDictionary.update(Counter(tokensFiltered))\ngrams = ngrams(tokensFiltered,2)\nbigramsDictionary.update(Counter(grams))\n\nfor key,val in bigramsDictionary.items():\n\tp = \"p(\"+key[0]+\"/\"+key[1]+\")\"\n\tbigramsProbability[p] = float(val)/unigramsDictionary[key[0]]\n\nf = open('bigramsProbability.csv','w')\nwith f:\n\twriter =csv.writer(f)\n\twriter.writerows(bigramsProbability.items())\nf.close\n","repo_name":"nandakishor123/Fake-review-detection","sub_path":"bigramProbability.py","file_name":"bigramProbability.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"45734158222","text":"# import pandas as pd\r\n\r\nfrom sklearn.metrics import r2_score\r\nimport sys\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\nfrom sklearn import svm\r\nfrom mpl_toolkits.mplot3d import axes3d, Axes3D\r\nimport pandas as pd\r\nimport pickle\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.metrics import r2_score\r\n# str = sys.argv[1]\r\n# print(str)\r\n# str = sys.argv[2]\r\n# print(str)\r\n# print('INI SVRPSO')\r\n\r\ndef daily_increase(data):\r\n d = [] \r\n for i in range(len(data)):\r\n if i == 0:\r\n d.append(data[0])\r\n else:\r\n d.append(data[i]-data[i-1])\r\n return d \r\n\r\n\r\nconfirmed_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\r\nconfirmed_df = confirmed_df[confirmed_df['Country/Region']=='Indonesia']\r\n\r\n\r\ncols = confirmed_df.keys()\r\n\r\nconfirmed = confirmed_df.loc[:, cols[4]:cols[-1]]\r\ndates = confirmed.keys()\r\nworld_cases = []\r\n\r\nfor i in dates:\r\n confirmed_sum = confirmed[i].sum()\r\n world_cases.append(confirmed_sum)\r\ndays_since_1_22 = np.array([i for i in range(len(dates))]).reshape(-1, 1) # hari ke index\r\nworld_cases = np.array(world_cases).reshape(-1, 1)\r\narr = []\r\nfor x in range(len(world_cases)):\r\n dict_ = {'x':world_cases[x][0]}\r\n arr.append(dict_)\r\n # print(world_cases[x])\r\ndata = pd.DataFrame(arr)\r\n\r\nstart = int(sys.argv[2])\r\nend = sys.argv[1]\r\ntipe = sys.argv[3]\r\n# print(start)\r\n# print(start)\r\n# print(end)\r\n# print(tipe)\r\nmodel_name='psosvrakumulasi.sav'\r\nif tipe=='harian':\r\n model_name ='psosvrharian.sav'\r\n data['x'] = daily_increase(data['x'])\r\n\r\ndata = data['x'][int(start):int(end)].reset_index()['x']\r\ndata_n = data.copy()\r\ndata_n = (data - 0)/(data.max() - 0)\r\ndimensions = 12\r\ndata_cn = pd.concat([data_n.shift(i) for i in range(0 + dimensions + 1)], axis = 1)\r\ny=data_cn.iloc[12:,0]\r\nx = data_cn.iloc[12:,1:]\r\nloaded_model = pickle.load(open(model_name, 'rb'))\r\ntry:\r\n predict = loaded_model.predict(data_cn.iloc[12:,1:])\r\nexcept Exception as e:\r\n print(e)\r\ny = data_cn.iloc[12:,0]\r\nprint(predict*data.to_numpy().max())\r\nprint('%%'+str(r2_score(y*data.to_numpy().max(),predict*data.to_numpy().max())))\r\n#print('lancar')\r\n","repo_name":"IsnainiNurul/backup_ta","sub_path":"public/svrpso.py","file_name":"svrpso.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"24638519255","text":"n = 2\r\ncount = 0\r\nwhile(count < 5):\r\n isPrime = True\r\n i = 2\r\n while(i/', views.UpdateCodes.as_view(), name='single-code'),\n path('promoCodes/', views.CodeList.as_view(), name='all-codes'),\n path('activeCodes/', views.ActiveCodeList.as_view(), name='active-codes'),\n # testCode requires three parameters; code, valid origin & destination name\n # [only letter,numbers,underscores,hyphens allowed in names]\n path('testCode///', views.test_code, name='test-code')\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","repo_name":"Maseline/promo_code_api","sub_path":"api/promoCodeApi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"35548502807","text":"import os\n\nfrom ..java import (\n Class as JavaClass, Code as JavaCode, Method as JavaMethod, SourceFile,\n opcodes as JavaOpcodes\n)\nfrom .blocks import Block\nfrom .methods import (\n CO_GENERATOR, GeneratorFunction, Function,\n)\nfrom .utils import ALOAD_name, ASTORE_name, free_name\n\n\nclass Module(Block):\n def __init__(self, namespace, sourcefile, verbosity=0):\n super().__init__(verbosity=verbosity)\n self.sourcefile = sourcefile\n\n parts = os.path.splitext(sourcefile)[0].split(os.path.sep)\n if parts[-1] == '__init__':\n parts.pop()\n\n # If the sourcefile started with a /, the first part will\n # be an empty string; replace that with the namespace.\n # Otherwise, prepend the namespace to the parts.\n if parts[0] == '':\n parts[0] = namespace\n else:\n parts = [namespace] + parts\n self.namespace = '.'.join(parts[:-1])\n self.name = parts[-1]\n\n self.functions = []\n self.classes = []\n self.anonymous_inner_class_count = 0\n\n # Preallocate space for self when\n # the module static block is invoked\n self.parameters = [None]\n self.local_vars['self'] = 0\n\n @property\n def module(self):\n return self\n\n @property\n def full_name(self):\n return '.'.join(self.namespace.split('.')[1:] + [self.name])\n\n @property\n def descriptor(self):\n return '/'.join(self.namespace.split('.') + [self.name])\n\n @property\n def class_name(self):\n return '.'.join(self.namespace.split('.') + [self.name, '__init__'])\n\n @property\n def class_descriptor(self):\n return '/'.join(self.namespace.split('.') + [self.name, '__init__'])\n\n # def visitor_setup(self):\n # self.add_opcodes(\n # JavaOpcodes.LDC_W(\"STATIC BLOCK OF \" + self.class_name),\n # JavaOpcodes.INVOKESTATIC('org/Python', 'debug', '(Ljava/lang/String;)V'),\n # )\n\n def store_name(self, name):\n self.add_opcodes(\n ASTORE_name(self, '#value'),\n JavaOpcodes.GETSTATIC('python/sys/__init__', 'modules', 'Lorg/python/types/Dict;'),\n\n JavaOpcodes.NEW('org/python/types/Str'),\n JavaOpcodes.DUP(),\n JavaOpcodes.LDC_W(self.full_name),\n JavaOpcodes.INVOKESPECIAL('org/python/types/Str', '', '(Ljava/lang/String;)V'),\n\n JavaOpcodes.INVOKEINTERFACE('org/python/Object', '__getitem__', '(Lorg/python/Object;)Lorg/python/Object;'),\n JavaOpcodes.CHECKCAST('org/python/types/Module'),\n\n JavaOpcodes.LDC_W(name),\n ALOAD_name(self, '#value'),\n\n JavaOpcodes.INVOKEINTERFACE('org/python/Object', '__setattr__', '(Ljava/lang/String;Lorg/python/Object;)V'),\n )\n free_name(self, '#value')\n\n def store_dynamic(self):\n self.add_opcodes(\n ASTORE_name(self, '#value'),\n JavaOpcodes.GETSTATIC('python/sys/__init__', 'modules', 'Lorg/python/types/Dict;'),\n\n JavaOpcodes.NEW('org/python/types/Str'),\n JavaOpcodes.DUP(),\n JavaOpcodes.LDC_W(self.full_name),\n JavaOpcodes.INVOKESPECIAL('org/python/types/Str', '', '(Ljava/lang/String;)V'),\n\n JavaOpcodes.INVOKEINTERFACE('org/python/Object', '__getitem__', '(Lorg/python/Object;)Lorg/python/Object;'),\n JavaOpcodes.CHECKCAST('org/python/types/Module'),\n\n JavaOpcodes.GETFIELD('org/python/types/Module', '__dict__', 'Ljava/util/Map;'),\n\n ALOAD_name(self, '#value'),\n JavaOpcodes.INVOKEINTERFACE('java/util/Map', 'putAll', '(Ljava/util/Map;)V'),\n )\n free_name(self, '#value')\n\n def load_name(self, name):\n self.add_opcodes(\n JavaOpcodes.GETSTATIC('python/sys/__init__', 'modules', 'Lorg/python/types/Dict;'),\n\n JavaOpcodes.NEW('org/python/types/Str'),\n JavaOpcodes.DUP(),\n JavaOpcodes.LDC_W(self.full_name),\n JavaOpcodes.INVOKESPECIAL('org/python/types/Str', '', '(Ljava/lang/String;)V'),\n\n JavaOpcodes.INVOKEINTERFACE('org/python/Object', '__getitem__', '(Lorg/python/Object;)Lorg/python/Object;'),\n JavaOpcodes.CHECKCAST('org/python/types/Module'),\n JavaOpcodes.LDC_W(name),\n JavaOpcodes.INVOKEINTERFACE('org/python/Object', '__getattribute__', '(Ljava/lang/String;)Lorg/python/Object;'),\n )\n\n def delete_name(self, name):\n self.add_opcodes(\n JavaOpcodes.GETSTATIC('python/sys/__init__', 'modules', 'Lorg/python/types/Dict;'),\n\n JavaOpcodes.NEW('org/python/types/Str'),\n JavaOpcodes.DUP(),\n JavaOpcodes.LDC_W(self.full_name),\n JavaOpcodes.INVOKESPECIAL('org/python/types/Str', '', '(Ljava/lang/String;)V'),\n\n JavaOpcodes.INVOKEINTERFACE('org/python/Object', '__getitem__', '(Lorg/python/Object;)Lorg/python/Object;'),\n JavaOpcodes.CHECKCAST('org/python/types/Module'),\n JavaOpcodes.LDC_W(name),\n JavaOpcodes.INVOKEVIRTUAL('org/python/types/Module', '__delattr__', '(Ljava/lang/String;)V'),\n )\n\n def add_function(self, name, code, parameter_signatures, return_signature):\n if code.co_flags & CO_GENERATOR:\n # Generator method.\n function = GeneratorFunction(\n self,\n name=name,\n code=code,\n generator=code.co_name,\n parameters=parameter_signatures,\n returns=return_signature,\n static=True\n )\n else:\n # Normal function.\n function = Function(\n self,\n name=name,\n code=code,\n parameters=parameter_signatures,\n returns=return_signature,\n static=True,\n )\n\n # Add the function to the list that need to be\n # transpiled into Java functions\n self.functions.append(function)\n\n # Add a definition of the callable object\n self.add_callable(function)\n\n return function\n\n def add_class(self, class_name, bases, extends, implements):\n from .klass import Class\n\n klass = Class(\n self,\n name=class_name,\n bases=[\n 'org/python/Object' if b == 'object' else b\n for b in bases\n ],\n extends=extends,\n implements=implements,\n )\n\n self.classes.append(klass)\n\n self.add_opcodes(\n # JavaOpcodes.LDC_W(\"FORCE LOAD OF CLASS %s AT DEFINITION\" % self.klass.descriptor),\n # JavaOpcodes.INVOKESTATIC('org/Python', 'debug', '(Ljava/lang/String;)V'),\n\n JavaOpcodes.LDC_W(klass.descriptor.replace('/', '.')),\n JavaOpcodes.INVOKESTATIC('java/lang/Class', 'forName', '(Ljava/lang/String;)Ljava/lang/Class;'),\n\n JavaOpcodes.INVOKESTATIC('org/python/types/Type', 'pythonType', '(Ljava/lang/Class;)Lorg/python/types/Type;'),\n )\n\n self.store_name(klass.name)\n\n return klass\n\n def visitor_teardown(self):\n self.add_opcodes(\n JavaOpcodes.RETURN(),\n )\n\n def transpile(self):\n \"\"\"Convert a materialized Python code definition into a list of Java\n Classfile definitions.\n\n Returns a list of triples:\n (namespace, class_name, javaclassfile)\n\n The list contains the classfile for the module, plus and classes\n defined in the module.\n \"\"\"\n # If there is any static content, generate a classfile\n # for this module\n classfile = JavaClass(self.class_descriptor, extends='org/python/types/Module')\n classfile.attributes.append(SourceFile(os.path.basename(self.sourcefile)))\n\n # Add a static method to the module, populated with the\n # body content of the module.\n static_init = JavaMethod('module$import', '()V', public=False)\n static_init.attributes.append(self.transpile_code())\n classfile.methods.append(static_init)\n\n # Add a dummy init method.\n classfile.methods.append(\n JavaMethod(\n '',\n '()V',\n attributes=[\n JavaCode(\n max_stack=2,\n max_locals=1,\n code=[\n JavaOpcodes.ALOAD_0(),\n JavaOpcodes.DUP(),\n JavaOpcodes.INVOKESPECIAL('org/python/types/Module', '', '()V'),\n JavaOpcodes.RETURN(),\n ],\n ),\n ]\n )\n )\n\n # Add any static methods defined in the module\n for function in self.functions:\n classfile.methods.extend(function.transpile())\n\n # The list of classfiles that will be returned will contain\n # at least one entry - the class for the module itself.\n classfiles = [(\n self.namespace,\n '%s/__init__' % self.name,\n classfile\n )]\n # Also output any classes defined in this module.\n for klass in self.classes:\n classfiles.append(klass.transpile())\n\n return classfiles\n","repo_name":"candeira/voc","sub_path":"voc/python/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":9334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"80"} +{"seq_id":"74448218497","text":"from Src.SystemImport import SystemImport\nfrom Src.PortInterface import PortInterfaces\nfrom Src.DataType import DataTypes\nimport autosar\nimport re\n\nclass Components:\n def __init__(self, syscomponents, ws):\n swcomponentpackage = ws.createPackage('ComponentTypes', role='ComponentType')\n self.childcomponent = {}\n self.childcomposition = {}\n self.fathercomposition = None\n\n for swc in syscomponents:\n # print(swc)\n if 'APP-SWC' == swc['componenttype']:\n swc1 = swcomponentpackage.createApplicationSoftwareComponent(swc['swc name'])\n self.childcomponent[swc['swc name']] = swc1\n if 'APP-COMP' == swc['componenttype']:\n swc1 = swcomponentpackage.createCompositionComponent(swc['swc name'])\n self.childcomposition[swc['swc name']] = swc1\n if 'DELEGATION' == swc['componenttype']:\n swc1 = swcomponentpackage.createCompositionComponent(swc['swc name'])\n self.fathercomposition = swc1\n for ele in swc['elements']:\n if 'Port' == ele['attributes']:\n if 'Provider' == ele['direction']:\n swc1.createProvidePort(ele['portname'], ws.findRolePackage('PortInterface').find(ele['interfaces']).ref)\n if 'Receiver' == ele['direction']:\n swc1.createRequirePort(ele['portname'], ws.findRolePackage('PortInterface').find(ele['interfaces']).ref)\n if 'Server' == ele['direction']:\n swc1.createProvidePort(ele['portname'], ws.findRolePackage('PortInterface').find(ele['interfaces']).ref)\n if 'APP-SWC' == swc['componenttype']:\n for op in ws.findRolePackage('PortInterface').find(ele['interfaces']).operations:\n swc1.behavior.createRunnable(ele['portname'] + \"_\" + op.name)\n swc1.behavior.createOperationInvokedEvent(ele['portname'] + \"_\" + op.name, ele['portname'] + \"/\" + op.name)\n if 'Client' == ele['direction']:\n swc1.createRequirePort(ele['portname'], ws.findRolePackage('PortInterface').find(ele['interfaces']).ref)\n for x in self.childcomponent.values():\n self.fathercomposition.createComponentPrototype(x.ref)\n for y in self.childcomposition.values():\n self.fathercomposition.createComponentPrototype(y.ref)\n\n for swc in syscomponents:\n # print(swc)\n for ele in swc['elements']:\n if None != ele['receiver swc']:\n for rswc in ele['receiver swc']:\n if rswc in self.childcomponent:\n port = self.childcomponent[rswc].createRequirePort(ele['portname'].replace('P_','R_'), ws.findRolePackage('PortInterface').find(ele['interfaces']).ref)\n if 'DELEGATION' == swc['componenttype']:\n self.fathercomposition.createConnector(ele['portname'], port.ref)\n else:\n self.fathercomposition.createConnector(swcomponentpackage.ref + '/' + swc['swc name'] + '/' + ele['portname'], port.ref)\n if rswc in self.childcomposition:\n port = self.childcomposition[rswc].createRequirePort(ele['portname'].replace('P_','R_') ,ws.findRolePackage('PortInterface').find(ele['interfaces']).ref)\n if 'DELEGATION' == swc['componenttype']:\n self.fathercomposition.createConnector(ele['portname'], port.ref)\n else:\n self.fathercomposition.createConnector(swcomponentpackage.ref + '/' + swc['swc name'] + '/' + ele['portname'], port.ref)\n if 'Delegation' == rswc:\n port = self.fathercomposition.createProvidePort(ele['portname'], ws.findRolePackage('PortInterface').find(ele['interfaces']).ref)\n self.fathercomposition.createConnector(swcomponentpackage.ref + '/' + swc['swc name'] + '/' + ele['portname'], ele['portname'])\n\n for swc in syscomponents:\n portinterfaces = ws.findRolePackage('PortInterface')\n for ele in swc['elements']:\n if 'Task' == ele['attributes']:\n if 'INIT' == ele['schedule']:\n if 'Yes' == ele['defaultportaccess']:\n portAccessList = self.findportaccesstable(swc['swc name'], portinterfaces)\n self.childcomponent[swc['swc name']].behavior.createRunnable(swc['swc name'] + '_' + ele['portname'], portAccess=portAccessList)\n self.childcomponent[swc['swc name']].behavior.createInitEvent(swc['swc name'] + '_' + ele['portname'])\n else:\n self.childcomponent[swc['swc name']].behavior.createRunnable(swc['swc name'] + '_' + ele['portname'])\n self.childcomponent[swc['swc name']].behavior.createInitEvent(swc['swc name'] + '_' + ele['portname'])\n else:\n if 'Yes' == ele['defaultportaccess']:\n portAccessList = self.findportaccesstable(swc['swc name'], portinterfaces)\n self.childcomponent[swc['swc name']].behavior.createRunnable(swc['swc name'] + '_' + ele['portname'], portAccess=portAccessList)\n self.childcomponent[swc['swc name']].behavior.createTimerEvent(swc['swc name'] + '_' + ele['portname'], int(re.findall(r'\\d+', ele['schedule'])[0]))\n else:\n self.childcomponent[swc['swc name']].behavior.createRunnable(swc['swc name'] + '_' + ele['portname'])\n self.childcomponent[swc['swc name']].behavior.createTimerEvent(swc['swc name'] + '_' + ele['portname'], int(re.findall(r'\\d+', ele['schedule'])[0]))\n def findportaccesstable(self, swcname, pipackage):\n portAccessList = []\n swcports = self.childcomponent[swcname].requirePorts\n for port in swcports:\n portref = pipackage.find(port.portInterfaceRef)\n if isinstance(portref, autosar.portinterface.SenderReceiverInterface):\n portelements = [x.name for x in portref.dataElements]\n for ele in portelements:\n portAccessList.append(port.name + \"/\" + ele)\n if isinstance(portref, autosar.portinterface.ClientServerInterface):\n portelements = [x.name for x in portref.operations]\n for ele in portelements:\n portAccessList.append(port.name + \"/\" + ele)\n swcports = self.childcomponent[swcname].providePorts\n for port in swcports:\n portref = pipackage.find(port.portInterfaceRef)\n if isinstance(portref, autosar.portinterface.SenderReceiverInterface):\n portelements = [x.name for x in portref.dataElements]\n for ele in portelements:\n portAccessList.append(port.name + \"/\" + ele)\n return portAccessList\n\nif __name__ == '__main__':\n System = SystemImport('../Import/Application.xlsx')\n ws = autosar.workspace('4.2.2')\n DataTypes(System, ws)\n PortInterfaces(System, ws)\n Components(System.swcomponentlist, ws)\n ws.saveXML('../Export/Application.arxml')","repo_name":"PeaceZhang/ArxmlTools","sub_path":"Src/Component.py","file_name":"Component.py","file_ext":"py","file_size_in_byte":7550,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"19177708788","text":"\"\"\"\nclient\n\nincludes variables important to the function of the bot\n\"\"\"\n#pylint:disable=global-at-module-level\n#pylint:disable=invalid-name\n\nimport asyncio\n\nimport discord\n\nglobal loop\nloop = asyncio.new_event_loop()\n\nglobal BOT_STATUS\nBOT_STATUS = False\n\nglobal client\nclient = discord.Client(loop=loop)\n","repo_name":"zwang20/deployment-bot-6","sub_path":"client/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"41176101171","text":"# -*- coding: utf-8 -*-\n#\nfrom datetime import datetime\nfrom websockets import connect\n\nasync def listen(uri, ssl_context):\n async with connect(uri, ssl=ssl_context) as ws:\n while True:\n msg = await ws.recv()\n print(f'{datetime.now().isoformat()}: {msg}')\n","repo_name":"artsman/omnis_wsbus","sub_path":"omnis_wsbus/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"71394448259","text":"import pandas as pd\nimport numpy as np\nimport configparser\nimport logging\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import Dense\nfrom scikeras.wrappers import KerasClassifier\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold, train_test_split, cross_val_predict\nfrom sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score\nfrom servier.feature_extractor import fingerprint_features # Assuming this is a custom module\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# Configuring logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\n# Read config file\nconfig = configparser.ConfigParser()\ntry:\n config.read('servier/config.ini')\n logging.info(\"Config file loaded successfully.\")\nexcept Exception as e:\n logging.error(f\"Error reading the config file: {e}\")\n raise\n\n# Constants from config file\nDATASET_SINGLE_PATH = config['DEFAULT']['DATASET_SINGLE_PATH']\nMODEL_1_PATH = config['DEFAULT']['MODEL_1_PATH']\n\n\n# Function to load dataset\ndef load_dataset(file_path):\n try:\n data = pd.read_csv(file_path)\n logging.info(f\"Dataset loaded from {file_path}\")\n return data\n except Exception as e:\n logging.error(f\"Error loading dataset: {e}\")\n raise\n\n# Optimized feature extraction\ndef extract_features(smiles):\n try:\n features = np.frombuffer(fingerprint_features(smiles).ToBitString().encode(), 'u1') - ord('0')\n return features\n except Exception as e:\n logging.error(f\"Error extracting features for SMILES {smiles}: {e}\")\n return None\n\n# Load the dataset\ndf = load_dataset(DATASET_SINGLE_PATH)\n\n# Extract features and prepare the dataset\ntry:\n fingerprints = df['smiles'].apply(extract_features)\n X = pd.DataFrame(fingerprints.tolist(), columns=[f'Bit_{i}' for i in range(fingerprints.iloc[0].shape[0])])\n Y = df['P1']\n INPUT_SIZE = X.shape[1] # Update INPUT_SIZE based on the actual input features\n logging.info(\"Features extracted and dataset prepared\")\nexcept Exception as e:\n logging.error(f\"Error in feature extraction or dataset preparation: {e}\")\n raise\n\n# Split the dataset into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=.2, random_state=42)\n\n\ndef create_model_1():\n \"\"\"\n Create and return a Sequential model with specified layers and activation functions.\n\n Returns:\n model: A Sequential model with input, hidden, and output layers.\n \"\"\"\n # Create a Sequential model\n model = Sequential([\n Dense(1024, input_dim=INPUT_SIZE, activation='relu'),\n Dense(512, activation='relu'),\n Dense(256, activation='relu'),\n Dense(1, activation='sigmoid')\n ])\n \n # Compile the model\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n \n return model\n\ndef train_model_1(epochs=100, batch_size=64):\n \"\"\"\n Train the model on the training dataset and save it to a file.\n\n Parameters:\n epochs (int): The number of epochs for training the model.\n batch_size (int): The batch size for training the model.\n \"\"\"\n model_1 = create_model_1()\n model_1.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2)\n model_1.save(MODEL_1_PATH)\n logging.info(\"Model 1 saved.\")\n\n\ndef evaluate_model_1(epochs=100, batch_size=64, n_splits=5):\n \"\"\"\n Evaluate the model performance using cross-validation and compute additional metrics like precision, recall, and F1-score.\n\n Parameters:\n epochs (int): The number of epochs for training the model.\n batch_size (int): The batch size for training the model.\n n_splits (int): The number of folds in StratifiedKFold.\n\n Returns:\n dict: A dictionary containing cross-validation results, mean accuracy, \n standard deviation, precision, recall, and F1-score.\n \"\"\"\n try:\n estimator = KerasClassifier(build_fn=create_model_1, epochs=epochs, batch_size=batch_size)\n kfold = StratifiedKFold(n_splits=n_splits, shuffle=True)\n \n # Getting cross-validated predictions\n y_pred = cross_val_predict(estimator, X.values, Y.values, cv=kfold)\n \n # Computing metrics\n accuracy = accuracy_score(Y.values, y_pred)\n precision = precision_score(Y.values, y_pred)\n recall = recall_score(Y.values, y_pred)\n f1 = f1_score(Y.values, y_pred)\n conf_matrix = confusion_matrix(Y.values, y_pred)\n \n # Logging and returning results\n logging.info(f\"Accuracy: {accuracy}, Precision: {precision}, Recall: {recall}, F1-score: {f1}\")\n logging.info(f\"Confusion Matrix:\\n{conf_matrix}\")\n\n # Plotting confusion matrix\n plt.figure(figsize=(8, 6))\n sns.heatmap(conf_matrix, annot=True, fmt=\"g\", cmap='Blues', xticklabels=['0', '1'], yticklabels=['0', '1'])\n plt.xlabel('Predicted')\n plt.ylabel('True')\n plt.title('Confusion Matrix')\n plt.show()\n\n return {\"precision\": precision, \"recall\": recall, \"f1_score\": f1, \"confusion_matrix\": conf_matrix}\n\n except Exception as e:\n logging.error(f\"Error during model evaluation: {e}\")\n raise\n \ndef load_trained_model():\n try:\n loaded_model = load_model(MODEL_1_PATH)\n logging.info(\"Model loaded successfully.\")\n return loaded_model\n except Exception as e:\n logging.error(f\"Error loading model: {e}\")\n raise\n\n\n\ndef predict_model_1(smiles):\n \"\"\"\n Predict the binary property of a given SMILES string using the trained model.\n\n Parameters:\n smiles (str): The SMILES string of the chemical compound.\n\n Returns:\n tuple: Binary prediction (1 or 0).\n \"\"\"\n loaded_model = load_trained_model()\n\n try:\n features = np.frombuffer(fingerprint_features(smiles).ToBitString().encode(), 'u1') - ord('0')\n prediction = loaded_model.predict(np.array([features]))\n \n binary_prediction = 1 if prediction >= 0.5 else 0\n logging.info(f\"Prediction: {binary_prediction}, Probability: {prediction[0][0]}\")\n \n return binary_prediction\n \n except Exception as e:\n logging.error(f\"Error during prediction for SMILES {smiles}: {e}\")\n raise\n ","repo_name":"ouahbi13/servier-technical-test","sub_path":"servier/model_1.py","file_name":"model_1.py","file_ext":"py","file_size_in_byte":6400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"1471792536","text":"# coding: utf-8\n\"\"\"zmq constants\"\"\"\n\nfrom ._cffi import ffi, lib as C\nfrom zmq.utils.constant_names import all_names, no_prefix\n\nc_constant_names = ['PYZMQ_DRAFT_API']\nfor name in all_names:\n if no_prefix(name):\n c_constant_names.append(name)\n else:\n c_constant_names.append(\"ZMQ_\" + name)\n\n\ng = globals()\nfor cname in c_constant_names:\n if cname.startswith(\"ZMQ_\"):\n name = cname[4:]\n else:\n name = cname\n g[name] = getattr(C, cname)\n\nDRAFT_API = C.PYZMQ_DRAFT_API\n__all__ = ['DRAFT_API'] + all_names\n","repo_name":"thebaselab/codeapp","sub_path":"LanguageResources/Library/lib/python3.9/site-packages/zmq/backend/cffi/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":2422,"dataset":"github-code","pt":"80"} +{"seq_id":"24603185923","text":"#!/usr/bin/python3\n\nimport numpy as np\nimport cv2\nfrom tqdm import tqdm \nfrom skimage.morphology import skeletonize \nimport sys\nimport skvideo.io \nimport argparse\n\n'''\nauthor : Matteo Adorisio (@mattadori) and Shivansh (@dave-shivansh)\n@Qbio summer school KITP 2018 - Liao Zfish module\n'''\n\ndef get_background(filename,T,old_bg,bg_path,debug):\n \n background_image = filename+'.bg.png'\n if old_bg or bg_path :\n if bg_path :\n background_image = bg_path\n bg = cv2.imread(background_image)\n bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY) \n else :\n if debug:\n print('Computing background - ',background_image)\n \n cap = cv2.VideoCapture(filename) \n total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n \n nf = 0\n imgs = []\n for f in tqdm(range(total_frames)):\n ret, frame = cap.read()\n nf += 1 \n if nf % T == 0: \n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n imgs.append(frame_gray)\n\n bg = np.median(np.asarray(imgs),axis=0).astype(np.uint8)\n cv2.imwrite(background_image, bg)\n if debug:\n print('Background used - ',background_image)\n return(bg)\n\ndef get_roi(filename,old_roi,roi_path,debug):\n\n roi_name = filename+'.roi'\n if old_roi or roi_path :\n if roi_path :\n roi_name = roi_path\n roi_file = open(roi_name,'r')\n roi = roi_file.readline()\n roi = [int(s) for s in roi.split() if s.isdigit()]\n else :\n if debug:\n print('Setting ROI - ',roi_name)\n \n cap = cv2.VideoCapture(filename) \n ret, frame = cap.read()\n cap.release()\n\n roi = cv2.selectROI(frame)\n cv2.destroyAllWindows() \n \n roi_file = open(roi_name,'w')\n roi_file.write(\"{} {} {} {}\".format(int(roi[0]),int(roi[1]),int(roi[2]),int(roi[3])))\n roi_file.close()\n if debug:\n print('ROI - ',roi, roi_name)\n return(roi)\n\ndef track_fish(videofile,bg,roi,no_show,debug):\n if debug:\n print(\"Starting fish tracking...\")\n \n\n bg = bg[int(roi[1]):int(roi[1]+roi[3]), int(roi[0]):int(roi[0]+roi[2])]\n\n annotated_video = skvideo.io.FFmpegWriter(videofile+\"--ANNOTATED.mp4\")\n outfile = open(videofile+'.dat','w')\n outfile.write(\"# stim 0\\n\")\n outfile.write(\"# xr,yr 'tail' --- xl,yl 'head' \\n\")\n outfile.write(\"# 1:frame 2:xl 3:yl 4:xr 5:yr\\n\")\n\n cap = cv2.VideoCapture(videofile)\n totframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n ret, frame = cap.read()\n\n if debug: \n print(\"Tracking fish - \",videofile, no_show)\n\n f = 0 #frame \n while(ret):\n f += 1 \n frame = frame[int(roi[1]):int(roi[1]+roi[3]), int(roi[0]):int(roi[0]+roi[2])] \n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n \n fg = cv2.subtract(bg,frame_gray) \n _, fg = cv2.threshold(fg, 10, 255, cv2.THRESH_BINARY)\n morph_kernel = np.ones((3,3),np.uint8)\n fg = cv2.morphologyEx(fg, cv2.MORPH_CLOSE, morph_kernel) # _OPEN \n _, contours, contours_hierarchy = cv2.findContours(fg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) \n mask = np.zeros(fg.shape,np.uint8)\n \n for c in contours:\n \n if cv2.contourArea(c)>2500:\n #skel_file = open(\"./skel.txt\",\"w\")\n #body_file = open(\"./body.txt\",\"w\")\n \n #square brackets for cv2.drawContours needs arrays of arrays as input\n cv2.drawContours(mask, [c],\n -1, # draw all contours (only one in this case)\n 255, #white\n -1) # draw contour's interior\n \n cv2.drawContours(frame_gray, [c],\n -1, \n 255,\n 1)\n \n pixelpoints = np.transpose(np.nonzero(mask))\n\n #for p in pixelpoints:\n # body_file.write(\"{} {}\\n\".format(p[0],p[1]))\n\n #M = cv2.moments(c)\n #cx = int(M[\"m10\"] / M[\"m00\"])\n #cy = int(M[\"m01\"] / M[\"m00\"])\n \n leftmost = c[c[:,:,0].argmin()][0]\n cv2.circle(frame_gray,tuple(leftmost), 4, (255,0,0), -1) \n rightmost = c[c[:,:,0].argmax()][0]\n cv2.circle(frame_gray,tuple(rightmost), 4, (255,0,0), -1) \n \n outfile.write(\"{} {} {} {} {}\\n\".format(f,leftmost[0],leftmost[1],rightmost[0],rightmost[1]))\n \n skel = skeletonize(np.asarray(mask/255,dtype=np.uint8)).astype(np.uint8)\n #skel = thin(np.asarray(mask/255,dtype=np.uint8),max_iter=10).astype(np.uint8)\n pixelskel = np.transpose(np.nonzero(skel))\n\n #leftmost = pixelskel[pixelskel[:,1].argmin(),:]\n #rightmost = pixelskel[pixelskel[:,1].argmax(),:]\n \n #pixelskel = np.append(pixelskel,[np.asarray([leftmost[1],leftmost[0]])],axis=0) # add leftmost\n \n for p in pixelskel:\n cv2.circle(frame_gray,(p[1],p[0]), 1, (255,0,0), -1)\n #skel_file.write(\"{} {}\\n\".format(p[0],p[1]))\n \n #body_file.flush()\n #skel_file.flush()\n #body_file.close()\n #skel_file.close() \n \n cv2.putText(frame_gray, str(int(f))+'/'+str(totframes),(50,frame_gray.shape[0]-10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)\n \n \n annotated_video.writeFrame(frame_gray)\n \n ret, frame = cap.read()\n \n if not no_show : \n cv2.imshow('fg', frame_gray)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n cap.release()\n cv2.destroyAllWindows()\n annotated_video.close()\n outfile.close()\n\n\nif __name__ == '__main__' :\n \n parser = argparse.ArgumentParser(description='Fish tracking')\n\n parser.add_argument(\"filename\", help='Video file name')\n parser.add_argument(\"--do_track\", dest='track_flag', action='store_true', help=\"Track fish\")\n\n parser.add_argument(\"--do_roi\", dest='roi_flag', action='store_true', help=\"Compute and save roi\")\n parser.add_argument(\"--old_roi\", dest='old_roi_flag', action='store_true', help=\"Use precomputed roi\")\n parser.add_argument(\"--roi_path\", default=None, help=\"Give custom roi path\")\n\n parser.add_argument(\"--do_bg\", dest='bg_flag', action='store_true', help=\"Compute background\")\n parser.add_argument(\"--old_bg\", dest='old_bg_flag', action='store_true', help=\"Use precomputed background\")\n parser.add_argument(\"--bg_path\", default=None, help=\"Give custom background\")\n\n parser.add_argument(\"--debug\", dest='db_flag', action='store_true', help=\"Debug\")\n parser.add_argument(\"--no-show\", dest='no_show_flag', action='store_true', help=\"Hide annotation (faster)\")\n \n args = parser.parse_args()\n bg_T = 10 # Select 1:bg_T files for bg compute\n \n if args.bg_flag or args.track_flag :\n bg = get_background(args.filename, bg_T, args.old_bg_flag, args.bg_path, args.db_flag)\n\n if args.roi_flag or args.track_flag :\n roi = get_roi(args.filename,args.old_roi_flag, args.roi_path, args.db_flag)\n \n if args.track_flag :\n track_fish(args.filename,bg,roi,args.no_show_flag,args.db_flag)\n\n exit()\n\n","repo_name":"ShivanshDave/qbio-zfish","sub_path":"tracking-code/track_zfish.py","file_name":"track_zfish.py","file_ext":"py","file_size_in_byte":7772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"29374371855","text":"DEPARTMENT_CHOICES = [\n (\"COMPS\", \"Computer\"),\n (\"IT\", \"Information Technology\"),\n (\"EXTC\", \"Electronics & Telecommunication\"),\n (\"PROD\", \"Production\"),\n (\"MECH\", \"Mechanical\"),\n (\"BIO\", \"Biomedical\"),\n (\"ELEX\", \"Electronics\"),\n (\"CHEM\", \"Chemical\"),\n]\n\nDEPARTMENT_CHOICES_COORD = [\n (\"COMPS\", \"Computer\"),\n (\"IT\", \"Information Technology\"),\n (\"EXTC\", \"Electronics & Telecommunication\"),\n (\"PROD\", \"Production\"),\n (\"MECH\", \"Mechanical\"),\n (\"BIO\", \"Biomedical\"),\n (\"ELEX\", \"Electronics\"),\n (\"CHEM\", \"Chemical\"),\n (\"HUM\", \"Science & Humanities\"),\n]\n\nYEAR_CHOICES = [(\"TE\", \"Third Year\"), (\"BE\", \"Fourth Year\")]\n\nROLE_CHOICES = [(\"STUDENT\", \"Student\"), (\"CO\", \"Co-ordinator\"), (\"TPO\", \"TPO\")]\n\nCATEGORY_CHOICES = [(\"S\", \"Super Dream\"), (\"D\", \"Dream\"), (\"R\", \"Regular\")]\n\nSTATUS_CHOICES = [\n (\"1\", \"Put Under Review\"),\n (\"2\", \"Scheduled For Interview\"),\n (\"3\", \"Selected\"),\n (\"4\", \"Rejected\"),\n]\n","repo_name":"djunicode/placement-portal-web","sub_path":"placementApp/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"37941252336","text":"from datetime import timedelta\n\nfrom django.contrib.auth import get_user_model\nfrom django.utils import timezone\n\nfrom misago.core.utils import slugify\n\nfrom .checksums import update_post_checksum\nfrom .models import Poll, Post, Thread\n\n\ndef post_thread(category, title='Test thread', poster='Tester',\n is_global=False, is_pinned=False, is_unapproved=False,\n is_hidden=False, is_closed=False, started_on=None):\n started_on = started_on or timezone.now()\n\n kwargs = {\n 'category': category,\n 'title': title,\n 'slug': slugify(title),\n 'started_on': started_on,\n 'last_post_on': started_on,\n 'is_unapproved': is_unapproved,\n 'is_hidden': is_hidden,\n 'is_closed': is_closed\n }\n\n if is_global:\n kwargs['weight'] = 2\n elif is_pinned:\n kwargs['weight'] = 1\n\n try:\n kwargs.update({\n 'starter': poster,\n 'starter_name': poster.username,\n 'starter_slug': poster.slug,\n 'last_poster': poster,\n 'last_poster_name': poster.username,\n 'last_poster_slug': poster.slug,\n })\n except AttributeError:\n kwargs.update({\n 'starter_name': poster,\n 'starter_slug': slugify(poster),\n 'last_poster_name': poster,\n 'last_poster_slug': slugify(poster),\n })\n\n thread = Thread.objects.create(**kwargs)\n reply_thread(\n thread,\n poster=poster,\n posted_on=started_on,\n is_hidden=is_hidden,\n is_unapproved=is_unapproved,\n )\n\n return thread\n\n\ndef reply_thread(thread, poster=\"Tester\", message=\"I am test message\",\n is_unapproved=False, is_hidden=False, is_event=False,\n has_reports=False, has_open_reports=False, posted_on=None, poster_ip='127.0.0.1'):\n posted_on = posted_on or thread.last_post_on + timedelta(minutes=5)\n\n kwargs = {\n 'category': thread.category,\n 'thread': thread,\n 'original': message,\n 'parsed': message,\n 'checksum': 'nope',\n 'poster_ip': poster_ip,\n 'posted_on': posted_on,\n 'updated_on': posted_on,\n 'is_event': is_event,\n 'is_unapproved': is_unapproved,\n 'is_hidden': is_hidden,\n 'has_reports': has_reports,\n 'has_open_reports': has_open_reports,\n }\n\n try:\n kwargs.update({'poster': poster, 'poster_name': poster.username})\n except AttributeError:\n kwargs.update({'poster_name': poster})\n\n post = Post.objects.create(**kwargs)\n\n update_post_checksum(post)\n post.save()\n\n thread.synchronize()\n thread.save()\n thread.category.synchronize()\n thread.category.save()\n\n return post\n\n\ndef post_poll(thread, poster):\n poll = Poll.objects.create(\n category=thread.category,\n thread=thread,\n poster=poster,\n poster_name=poster.username,\n poster_slug=poster.slug,\n poster_ip='127.0.0.1',\n question=\"Lorem ipsum dolor met?\",\n choices=[\n {\n 'hash': 'aaaaaaaaaaaa',\n 'label': 'Alpha',\n 'votes': 1\n },\n {\n 'hash': 'bbbbbbbbbbbb',\n 'label': 'Beta',\n 'votes': 0\n },\n {\n 'hash': 'gggggggggggg',\n 'label': 'Gamma',\n 'votes': 2\n },\n {\n 'hash': 'dddddddddddd',\n 'label': 'Delta',\n 'votes': 1\n }\n ],\n allowed_choices=2,\n votes=4\n )\n\n # one user voted for Alpha choice\n User = get_user_model()\n try:\n user = User.objects.get(slug='bob')\n except User.DoesNotExist:\n user = User.objects.create_user('bob', 'bob@test.com', 'Pass.123')\n\n poll.pollvote_set.create(\n category=thread.category,\n thread=thread,\n voter=user,\n voter_name=user.username,\n voter_slug=user.slug,\n voter_ip='127.0.0.1',\n choice_hash='aaaaaaaaaaaa'\n )\n\n # test user voted on third and last choices\n poll.pollvote_set.create(\n category=thread.category,\n thread=thread,\n voter=poster,\n voter_name=poster.username,\n voter_slug=poster.slug,\n voter_ip='127.0.0.1',\n choice_hash='gggggggggggg'\n )\n poll.pollvote_set.create(\n category=thread.category,\n thread=thread,\n voter=poster,\n voter_name=poster.username,\n voter_slug=poster.slug,\n voter_ip='127.0.0.1',\n choice_hash='dddddddddddd'\n )\n\n # somebody else voted on third option before being deleted\n poll.pollvote_set.create(\n category=thread.category,\n thread=thread,\n voter_name='deleted',\n voter_slug='deleted',\n voter_ip='127.0.0.1',\n choice_hash='gggggggggggg'\n )\n\n return poll\n\n\ndef like_post(post, user=None, username=None):\n if not post.last_likes:\n post.last_likes = []\n\n if user:\n like = post.postlike_set.create(\n category=post.category,\n thread=post.thread,\n user=user,\n user_name=user.username,\n user_slug=user.slug,\n user_ip='127.0.0.1'\n )\n\n post.last_likes = [\n {\n 'id': user.id,\n 'username': user.username\n }\n ] + post.last_likes\n else:\n like = post.postlike_set.create(\n category=post.category,\n thread=post.thread,\n user_name=username,\n user_slug=slugify(username),\n user_ip='127.0.0.1'\n )\n\n post.last_likes = [\n {\n 'id': None,\n 'username': username\n }\n ] + post.last_likes\n\n post.likes += 1\n post.save()\n\n return like\n","repo_name":"kinsney/education","sub_path":"misago/threads/testutils.py","file_name":"testutils.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"70852079619","text":"array = input().split('-')\r\nnums = []\r\nsums = 0\r\n\r\nfor i in array :\r\n k = i.split('+')\r\n num = 0\r\n for j in k :\r\n num += int(j)\r\n nums.append(num)\r\n\r\nsums = sum(nums[1 :])\r\nprint(nums[0] - sums)","repo_name":"ming018/Park_MG","sub_path":"백준/Silver/1541. 잃어버린 괄호/잃어버린 괄호.py","file_name":"잃어버린 괄호.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"28504143223","text":"import datetime\nimport os\nimport time\nfrom ansible.plugins.callback import CallbackBase\n\n\nclass CallbackModule(CallbackBase):\n \"\"\"\n A plugin for timing tasks\n \"\"\"\n def __init__(self):\n super(CallbackModule, self).__init__()\n self.stats = {}\n self.current = None\n\n def playbook_on_task_start(self, name, is_conditional):\n \"\"\"\n Logs the start of each task\n \"\"\"\n\n if os.getenv(\"ANSIBLE_PROFILE_DISABLE\") is not None:\n return\n\n if self.current is not None:\n # Record the running time of the last executed task\n self.stats[self.current] = time.time() - self.stats[self.current]\n\n # Record the start time of the current task\n self.current = name\n self.stats[self.current] = time.time()\n\n def playbook_on_stats(self, stats):\n \"\"\"\n Prints the timings\n \"\"\"\n\n if os.getenv(\"ANSIBLE_PROFILE_DISABLE\") is not None:\n return\n\n # Record the timing of the very last task\n if self.current is not None:\n self.stats[self.current] = time.time() - self.stats[self.current]\n\n # Sort the tasks by their running time\n results = sorted(\n self.stats.items(),\n key=lambda value: value[1],\n reverse=True,\n )\n\n # Just keep the top 10\n results = results[:10]\n\n # Print the timings\n for name, elapsed in results:\n print(\n \"{0:-<70}{1:->9}\".format(\n '{0} '.format(name),\n ' {0:.02f}s'.format(elapsed),\n )\n )\n\n total_seconds = sum([x[1] for x in self.stats.items()])\n print(\"\\nPlaybook finished: {0}, {1} total tasks. {2} elapsed. \\n\".format(\n time.asctime(),\n len(self.stats.items()),\n datetime.timedelta(seconds=(int(total_seconds)))\n )\n )\n","repo_name":"jlafon/ansible-profile","sub_path":"callback_plugins/profile_tasks.py","file_name":"profile_tasks.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":340,"dataset":"github-code","pt":"80"} +{"seq_id":"14188014334","text":"import os\r\nimport re\r\n\r\ntxt = input(\"input first paragraph (without .txt): \")\r\ntxtpath = os.path.join('Resources', txt + \".txt\")\r\nif not os.path.isfile(txtpath):\r\n\tprint(\"That .txt file does not exist\")\r\n\tquit()\r\n\r\nwith open(txtpath) as file:\r\n\tdata = file.read()\r\n\tdata_word = re.split('\\s+', data)\r\n\tdata_sent = re.split('\\S{3,}\\.\\s|\\S{3,}\\!\\s|\\?\\s|\\S{3,}\\.\\\"\\s', data)\r\n\tdata_word_clean = [i for i in data_word]\r\n\tdata_sent_split = [re.split('\\s+', i) for i in data_sent]\r\n\tavg_dwc = sum([len(i) for i in data_word_clean])/len(data_word_clean)\r\n\tavg_dss = sum([len(i) for i in data_sent_split])/len(data_sent_split)\r\n\tprint(\"\\nParagraph Analysis\")\r\n\tprint(\"-\" * 50)\r\n\tprint(\"Approximate Word Count: {}\".format(len(data_word)))\r\n\tprint(\"Approximate Sentence Count: {}\".format(len(data_sent)))\r\n\tprint(\"Average Letter Count: {:.2f}\".format(avg_dwc))\r\n\tprint(\"Average Sentence Length: {:.2f}\\n\".format(avg_dss))\r\n\r\n","repo_name":"jamiejin91/python-challenge","sub_path":"xJamieJin_HW3/PyParagraph.py","file_name":"PyParagraph.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"8845044966","text":"from math import sqrt\nimport util\n\n\ndef cancircle(xc, yc, r):\n pixels = []\n\n for x in range(int(xc), int(xc + int(r / sqrt(2)) + 1)):\n y = sqrt(r**2 - (x - xc)**2) + yc\n util.tmirrored(pixels, x, y, xc, yc)\n\n return pixels\n\n\ndef canellipse(xc, yc, rx, ry):\n pixels = []\n limit = int(xc + rx / sqrt(1 + ry**2 / rx**2))\n\n for x in range(int(xc), limit + 1):\n y = sqrt(rx**2 * ry**2 - (x - xc)**2 * ry**2) / rx + yc\n util.dmirrored(pixels, x, y, xc, yc)\n\n limit = int(yc + ry / sqrt(1 + rx**2 / ry**2))\n\n for y in range(limit, int(yc) - 1, -1):\n x = sqrt(rx**2 * ry**2 - (y - yc)**2 * rx**2) / ry + xc\n util.dmirrored(pixels, x, y, xc, yc,)\n\n return pixels\n","repo_name":"YaRamis/BMSTU_CG","sub_path":"ЛР 04/canonical.py","file_name":"canonical.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16082177839","text":"import numpy as np\nimport torch\nfrom scipy.spatial import Delaunay\nfrom time import time\nfrom math import ceil\n\nfrom ddsl import DDSL_spec\n\ndef rand_hull(n_points, dim, hull=False, dtype=torch.float32):\n V = np.random.rand(n_points, dim)\n mesh = Delaunay(V)\n E = mesh.simplices\n V, E = torch.tensor(V, dtype=dtype), torch.LongTensor(E)\n # normalize V to \n V_bb = torch.max(V, dim=0)[0] - torch.min(V, dim=0)[0]\n V_c = (torch.max(V, dim=0)[0] + torch.min(V, dim=0)[0]) / 2\n V -= V_c\n V /= 1.5*V_bb\n V += 0.5\n return V, E\n \ndef generate_random_mesh(j, dim, npoints, uniform_density=False, device=\"cuda\"):\n assert(j <= dim)\n dev = torch.device(device)\n \n if j == 0: # points\n V = torch.rand(npoints, dim, dtype=torch.float64)\n E = torch.arange(V.shape[0]).unsqueeze(-1)\n V, E = V.cuda(), E.cuda()\n V.requires_grad = True\n elif j == 1: # lines\n npoints = ceil(npoints / 2) * 2\n V = torch.rand(npoints, dim, dtype=torch.float64)\n E = torch.arange(V.shape[0]).view(-1, 2)\n elif j == 2: # triangles\n if dim == 2:\n V, E = rand_hull(npoints, dim, dtype=torch.float64)\n else:\n npoints = ceil(npoints / 3) * 3\n V = torch.rand(npoints, dim, dtype=torch.float64)\n E = torch.arange(V.shape[0]).view(-1, 3)\n elif j == 3: # tetrahedron\n if dim == 3:\n V, E = rand_hull(npoints, dim, dtype=torch.float64)\n else:\n npoints = ceil(npoints / 4) * 4\n V = torch.rand(npoints, dim, dtype=torch.float64)\n E = torch.arange(V.shape[0]).view(-1, 4)\n \n if uniform_density:\n D = torch.ones(E.shape[0], 1, dtype=V.dtype)\n else:\n D = torch.rand(E.shape[0], 1, dtype=V.dtype)\n V, E, D = V.to(dev), E.to(dev), D.to(dev)\n V.requires_grad = True\n \n return V, E, D\n\ndef test_ddsl(j, dim, npoints, res, accu=0.1, print_stats=False):\n # generate a random mesh\n V, E, D = generate_random_mesh(j, dim, npoints)\n\n res = [res] * dim\n t = [1] * dim\n\n # Sensitivity on each frequency mode\n r = res[0]\n if dim == 2:\n dF = torch.rand(r, int(r/2)+1, 1, 2, dtype=V.dtype, device=V.device) # unit sensitivity\n elif dim == 3:\n dF = torch.rand(r, r, int(r/2)+1, 1, 2, dtype=V.dtype, device=V.device) # unit sensitivity\n else:\n print(\"Test not implemented for dimensions other than 2 and 3.\")\n\n # Analytical Adjoint solution\n ddsl = DDSL_spec(res,t,j,1,'density')\n t0 = time()\n F = ddsl(V,E,D)\n t1 = time()\n loss = (F*dF).view(-1).sum(0)\n if V.grad is not None:\n V.grad.zero_()\n t2 = time()\n loss.backward()\n t3 = time()\n dV = V.grad\n\n # Finite difference approximation\n t4 = time()\n delta = 1e-6\n dV_fd_all = torch.zeros(*(list(V.shape)+list(dF.shape)), dtype=V.dtype).cuda()\n dD_fd_all = torch.zeros(*(list(D.shape)+list(dF.shape)), dtype=V.dtype).cuda()\n for ii in range(V.shape[0]):\n for jj in range(V.shape[1]):\n V_p = V.clone()\n V_m = V.clone()\n V_p[ii, jj] += delta\n V_m[ii, jj] -= delta\n Freq_p = ddsl(V_p, E, D)\n Freq_m = ddsl(V_m, E, D)\n dV_fd_all[ii,jj] = (Freq_p - Freq_m) / delta / 2\n for ii in range(D.shape[0]):\n for jj in range(D.shape[1]):\n D_p = D.clone()\n D_m = D.clone()\n D_p[ii, jj] += delta\n D_m[ii, jj] -= delta\n Freq_p = ddsl(V, E, D_p)\n Freq_m = ddsl(V, E, D_m)\n dD_fd_all[ii,jj] = (Freq_p - Freq_m) / delta / 2\n \n dV_fd = (dV_fd_all * dF).view(V.shape[0], V.shape[1], -1).sum(-1)\n dD_fd = (dD_fd_all * dF).view(D.shape[0], D.shape[1], -1).sum(-1)\n t5 = time()\n\n if print_stats:\n # Print analysis\n print(\"/ ***** Runtime Analysis ***** /\")\n print(\"Resolution: {}, # Elements: {}, Simplex Degree j: {}\".format(res, E.shape[0], E.shape[1]-1))\n print(\"Forward Time: {}\".format(t1-t0))\n print(\"Analytical Backward Time: {}\".format(t3-t2))\n print(\"Finite-Diff Backward Time: {}\".format(t5-t4))\n\n print(\"\\n/ ***** Correctness ***** /\")\n print(\"Analytical Gradient Matches Finite Difference Gradient to Accuracy {}:\".format(accu))\n print((torch.abs(dV - dV_fd) < accu).detach().cpu().numpy() == 1)\n print(\"\\n Analytical Gradient:\")\n print(dV.detach().cpu().numpy())\n print(\"Finite Difference Gradient:\")\n print(dV_fd.detach().cpu().numpy())\n \n match_V = torch.abs(dV - dV_fd) < accu\n match_D = torch.abs(dD - dD_fd) < accu\n pass_test_dV = (torch.sum(match_V) == match_V.numel()).detach().cpu().item() == 1\n pass_test_dD = (torch.sum(match_D) == match_D.numel()).detach().cpu().item() == 1\n \n return pass_test_dV, pass_test_dD\n\ndef test_ddsl_time(j, dim, npoints, res, ebatch, print_stats=False):\n # generate a random mesh\n V, E, D = generate_random_mesh(j, dim, npoints)\n\n res = [res] * dim\n t = [1] * dim\n\n # Sensitivity on each frequency mode\n r = res[0]\n if dim == 2:\n dF = torch.rand(r, int(r/2)+1, 1, 2, dtype=V.dtype, device=V.device) # unit sensitivity\n elif dim == 3:\n dF = torch.rand(r, r, int(r/2)+1, 1, 2, dtype=V.dtype, device=V.device) # unit sensitivity\n else:\n print(\"Test not implemented for dimensions other than 2 and 3.\")\n\n # Analytical Adjoint solution\n ddsl = DDSL_spec(res,t,j,elem_batch=ebatch,mode='density')\n t0 = time()\n F = ddsl(V,E,D)\n t1 = time()\n loss = (F*dF).view(-1).sum(0)\n if V.grad is not None:\n V.grad.zero_()\n t2 = time()\n loss.backward()\n t3 = time()\n fwd_time = t1-t0\n bwd_time = t3-t2\n if print_stats:\n print(\"/ ***** Runtime Analysis ***** /\")\n print(\"Resolution: {}, # Elements: {}, Simplex Degree j: {}\".format(res, E.shape[0], E.shape[1]-1))\n print(\"Forward Time: {}\".format(fwd_time))\n print(\"Analytical Backward Time: {}\".format(bwd_time))\n return fwd_time, bwd_time\n\nif __name__ == '__main__':\n # test_ddsl_time(3, 3, 200, 32, print_stats=True)\n import matplotlib as mpl; mpl.use('Agg')\n import matplotlib.pyplot as plt\n plt.rcParams.update({'font.size': 14})\n res = np.array([4, 8, 16, 32], dtype=np.int)\n ebatch = np.array([2000, 2000, 2000, 500, 100])\n forward_time = []\n backward_time = []\n for r, eb in zip(res, ebatch):\n ft, bt = test_ddsl_time(3, 3, 200, r, ebatch=eb, print_stats=True)\n forward_time.append(ft)\n backward_time.append(bt)\n forward_time = np.array(forward_time)\n backward_time = np.array(backward_time)\n plt.figure()\n plt.plot(res, forward_time, label='forward time')\n plt.plot(res, backward_time, label='backward time')\n plt.legend()\n plt.xlabel('resolution per dim')\n plt.ylabel('time (s)')\n plt.title('3D speed benchmark for tri mesh with ~1200 faces.')\n plt.savefig('speed3d.png')\n\n res = np.array([16, 32, 64, 128, 256], dtype=np.int)\n ebatch = np.array([2000, 2000, 2000, 500, 100])\n forward_time = []\n backward_time = []\n for r, eb in zip(res, ebatch):\n ft, bt = test_ddsl_time(2, 2, 130, r, ebatch=eb, print_stats=True)\n forward_time.append(ft)\n backward_time.append(bt)\n forward_time = np.array(forward_time)\n backward_time = np.array(backward_time)\n plt.figure()\n plt.plot(res, forward_time, label='forward time')\n plt.plot(res, backward_time, label='backward time')\n plt.legend()\n plt.xlabel('resolution per dim')\n plt.ylabel('time (s)')\n plt.title('2D speed benchmark for polygon with ~250 edges.')\n plt.savefig('speed2d.png')\n\n\n\n","repo_name":"maxjiang93/DDSL","sub_path":"ddsl/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":7732,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"80"} +{"seq_id":"16196874056","text":"\"\"\"\nDefinition of urls for BarcodeSystem.\n\"\"\"\n\nfrom datetime import datetime\nfrom django.conf.urls import url\nimport django.contrib.auth.views\nfrom django.conf.urls import include\nfrom django.contrib import admin#注意要加入此句,本人的问题就出在这里\nfrom basic import views as basic_views\nimport app.forms\nimport app.views\n\n# Uncomment the next lines to enable the admin:\n# from django.conf.urls import include\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = [\n # Examples:\n url(r'^$', app.views.home, name='home'),\n url(r'^contact$', app.views.contact, name='contact'),\n url(r'^about', app.views.about, name='about'),\n #url(r'^basic/barcodes$', basic_views.list_barcodes,name=\"listbarcodes\"),\n url(r'^login/$',\n django.contrib.auth.views.login,\n {\n 'template_name': 'app/login.html',\n 'authentication_form': app.forms.BootstrapAuthenticationForm,\n 'extra_context':\n {\n 'title': 'Log in',\n 'year': datetime.now().year,\n }\n },\n name='login'),\n #url(r'^register$',app.views.register,name='register'),\n #url(r'^saveUser$',app.views.saveUser,name='saveUser'),\n url(r'^logout$',\n django.contrib.auth.views.logout,\n {\n 'next_page': '/',\n },\n name='logout'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n]\n","repo_name":"hcsdn/Python-Barcode-System","sub_path":"BarcodeSystem/BarcodeSystem/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"2055807676","text":"#-*- encoding:utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport sys\nimport os\nimport pickle\nfrom sklearn.ensemble import GradientBoostingClassifier # 勾配ブースティング\nfrom sklearn.metrics import (roc_curve, auc, accuracy_score)\nfrom sklearn import tree # 可視化用\nimport pydotplus as pdp # 可視化用\n\n# 自作モジュール\nos.chdir('../') # カレントディレクトリを一階層上へ\nprint(os.getcwd())\nsys.path.append(os.path.join(os.path.dirname(__file__))) #パスの追加\nimport functions.evaluation_of_classifier as evaluation\n\n\nif __name__ == '__main__':\n usecols = [1,2,3,4,5,6,7,9,12,13]\n names = ('RCategory','WCategory', 'RTime', 'WTime', 'AccumulatedDis', 'Velocity', 'MVelocity', 'Distance', 'Target1', 'Target2')\n filename = \"./training_data/training_data.csv\"\n data_set = pd.read_csv(filename, sep = \",\", header = None, usecols = usecols, names=names)\n data_set = data_set.sample(frac=1).reset_index(drop=True) # データをシャッフル\n train_dataset, test_dataset = data_set[:int(0.8 * len(data_set))], data_set[int(0.8 * len(data_set)):] # 訓練データとテストデータに分割\n train_dataset1, test_dataset1 = train_dataset.drop(\"Target2\", axis = 1), test_dataset.drop(\"Target2\", axis = 1) # 停止セグメント\n train_dataset2, test_dataset2 = train_dataset.drop(\"Target1\", axis = 1), test_dataset.drop(\"Target1\", axis = 1) # 活動セグメント\n\n # モデルのfitとevaluate\n model1 = GradientBoostingClassifier(n_estimators=50, learning_rate=1.0, max_depth=1, random_state=777) # seedの設定。seedを設定しないとモデルが毎回変わるので注意\n model1 = evaluation.learn(model1, train_dataset1, \"Target1\")\n evaluation1 = evaluation.evaluate(model1, test_dataset1, \"Target1\")\n evaluation.output_csv(\"./models/bst/validation_r.csv\", model1, test_dataset1, \"Target1\", [\"REST_Proba\", \"GRAZE_Proba\"])\n\n model2 = GradientBoostingClassifier(n_estimators=50, learning_rate=1.0, max_depth=1, random_state=777) # seedの設定。seedを設定しないとモデルが毎回変わるので注意\n model2 = evaluation.learn(model2, train_dataset2, \"Target2\")\n evaluation2 = evaluation.evaluate(model2, test_dataset2, \"Target2\")\n evaluation.output_csv(\"./models/bst/validation_a.csv\", model2, test_dataset2, \"Target2\", [\"REST_Proba\", \"GRAZE_Proba\", \"WALK_Proba\"])\n\n print(evaluation1)\n print(evaluation2)\n\n # モデルを保存する\n filename1 = './models/bst/model.pickle'\n pickle.dump(model1, open(filename1, 'wb'))\n filename2 = './models/bst/model2.pickle'\n pickle.dump(model2, open(filename2, 'wb'))\n\n","repo_name":"FUKUSHUN/cow_python","sub_path":"COW_PROJECT/behavior_classification/models/boosting.py","file_name":"boosting.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"72761882497","text":"from lib.parse_meta import parse_meta\nimport glob\nimport os\n\n\nclean_dir = '/phoenix/S7/IARPA-SMART/datadump-1/KR-Pyeongchan/mvs_results/clean_data/'\n\nmin_alts = []\nmax_alts = []\nfor xml_file in glob.glob(os.path.join(clean_dir, '*.XML')):\n try:\n meta_dict = parse_meta(xml_file)\n rpc = meta_dict['rpc']\n min_val = -rpc['altScale'] + rpc['altOff']\n max_val = rpc['altScale'] + rpc['altOff']\n \n print(min_val, max_val)\n min_alts.append(min_val)\n max_alts.append(max_val)\n except:\n print(xml_file)\n\n\nprint('final:', max(min_alts), min(max_alts))\n\n","repo_name":"Kai-46/VisSatSatelliteStereo","sub_path":"precompute_altitude_range.py","file_name":"precompute_altitude_range.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"80"} +{"seq_id":"74993462659","text":"from rest_framework import viewsets\nfrom django.db.models import Q\nfrom common.helpers.response_helper import API_RESPONSE\nfrom organisation.models import Badge\nfrom organisation.serializers import BadgeListSerializer, BadgeUpdateSerializer\nfrom organisation.helper import (\n getDeletedTime,\n check_name,\n check_badge_type,\n insert_default_badges,\n)\nfrom common.swagger.documentation import (\n swagger_wrapper,\n swagger_auto_schema,\n type_param,\n)\nfrom drf_yasg import openapi\nimport logging\n\n\nclass BadgeAPI(viewsets.ViewSet):\n http_method_names = [\"get\", \"post\", \"put\", \"delete\"]\n\n @swagger_auto_schema(\n manual_parameters=[type_param],\n tags=[\"badge\"],\n )\n def list(self, request, *args, **kwargs):\n query_set = Q(\n organisation=request.data.get(\"organisation\", None),\n is_active=True,\n )\n type_param = self.request.query_params.get(\"type\", None)\n if Badge.objects.filter(query_set).count() == 0:\n insertion_status = insert_default_badges(\n request.data.get(\"organisation\", None), request.userinfo[\"id\"]\n )\n if not insertion_status:\n return API_RESPONSE.Return400Error(\"Failed to insert default badges\")\n if type_param not in [\"\", \" \", None, \"null\"]:\n query_set &= Q(\n type=type_param,\n status=True,\n )\n badges_list = Badge.objects.filter(query_set)\n return API_RESPONSE.Return200Success(\n \"Badges info\", BadgeListSerializer(badges_list, many=True).data\n )\n\n @swagger_wrapper(\n {\n \"name\": openapi.TYPE_STRING,\n \"colour\": openapi.TYPE_STRING,\n \"text_colour\": openapi.TYPE_STRING,\n \"type\": openapi.TYPE_STRING,\n },\n [\"badge\"],\n )\n def create(self, request, *args, **kwargs):\n if request.data.get(\"role\") != \"ADMIN\":\n return API_RESPONSE.Return400Error(\"You don't have permission\")\n\n badges_list = Badge.objects.filter(\n type=request.data.get(\"type\"),\n name=request.data.get(\"name\"),\n is_active=True,\n organisation=request.userinfo[\"organisation\"],\n )\n if badges_list.count() >= 1:\n return API_RESPONSE.Return400Error(\"name already exist\")\n\n error = check_name(request.data.get(\"name\"))\n if error:\n return API_RESPONSE.Return400Error(\"Invalid badge name\")\n\n error = check_badge_type(request.data.get(\"type\"))\n if error:\n return API_RESPONSE.Return400Error(\"Invalid badge provided\")\n\n badge = Badge(\n name=request.data.get(\"name\"),\n colour=request.data.get(\"colour\"),\n text_colour=request.data.get(\"text_colour\"),\n created_by=request.userinfo[\"id\"],\n type=request.data.get(\"type\"),\n organisation=request.userinfo[\"organisation\"],\n )\n badge.save()\n return API_RESPONSE.Return201Created(\n \"Badge Created Successfully\", BadgeListSerializer(badge).data\n )\n\n @swagger_wrapper(\n {\n \"name\": openapi.TYPE_STRING,\n \"colour\": openapi.TYPE_STRING,\n \"text_colour\": openapi.TYPE_STRING,\n },\n [\"badge\"],\n )\n def update(self, request, *args, **kwargs):\n try:\n if request.data.get(\"role\") != \"ADMIN\":\n return API_RESPONSE.Return400Error(\"You don't have permission\")\n\n badge_obj = Badge.objects.get(\n id=kwargs.get(\"pk\"),\n organisation=request.data.get(\"organisation\", None),\n is_active=True,\n )\n if \"name\" in request.data:\n try:\n error = check_name(request.data.get(\"name\"))\n if error:\n return API_RESPONSE.Return400Error(\"Invalid tag name\")\n\n existing_badge_obj = Badge.objects.get(\n name=request.data.get(\"name\"),\n type=badge_obj.type,\n is_active=True,\n organisation=request.data.get(\"organisation\"),\n )\n if existing_badge_obj.id != badge_obj.id:\n return API_RESPONSE.Return400Error(\"Name already exist\")\n except Exception:\n pass\n\n request.data[\"updated_by\"] = request.userinfo[\"id\"]\n serializer = BadgeUpdateSerializer(badge_obj, request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return API_RESPONSE.Return200Success(\"Badge updated\", serializer.data)\n return API_RESPONSE.Return400Error(\"Invalid data\")\n except Exception as err:\n logging.error(f\"BadgeAPI update: {err}\", exc_info=True)\n return API_RESPONSE.Return400Error(\"Not found\")\n\n def destroy(self, request, *args, **kwargs):\n try:\n if request.data.get(\"role\") != \"ADMIN\":\n return API_RESPONSE.Return400Error(\"You don't have permission\")\n\n badge_obj = Badge.objects.get(\n id=kwargs.get(\"pk\"),\n organisation=request.data.get(\"organisation\", None),\n is_active=True,\n )\n badge_obj.is_active = False\n badge_obj.deleted_by = request.data.get(\"user_id\")\n badge_obj.deleted_at = getDeletedTime()\n badge_obj.save()\n return API_RESPONSE.Return200Success(\n \"Badge deleted\",\n )\n except Exception as err:\n logging.error(f\"BadgeAPI destroy: {err}\", exc_info=True)\n return API_RESPONSE.Return400Error(\"Not found\")\n","repo_name":"lovingdreams/monitor","sub_path":"organisation/views/badges_views.py","file_name":"badges_views.py","file_ext":"py","file_size_in_byte":5820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"70547617538","text":"import sqlite3\n\nfrom dataclasses import dataclass\n\n@dataclass\nclass Note:\n id: int = None\n title: str = None\n content: str = ''\n\n\nclass Database:\n def __init__(self, nome):\n self.name = nome+'.db'\n self.conn = sqlite3.connect(self.name)\n self.conn.execute('''CREATE TABLE IF NOT EXISTS note ( id INTEGER PRIMARY KEY,\n title STRING,\n content STRING NOT NULL);''')\n \n def add(self, note : Note):\n self.conn.execute(\"INSERT INTO note (title, content) VALUES ('{0}', '{1}');\".format(note.title, note.content))\n self.conn.commit()\n\n def get_all(self):\n cursor = self.conn.execute(\"SELECT id, title, content FROM note\")\n lista = []\n for linha in cursor:\n note = Note(linha[0], linha[1], linha[2])\n lista.append(note)\n return lista\n \n def get_note(self, id):\n cursor = self.conn.execute(f\"SELECT id, title, content FROM note WHERE id = {id}\")\n linha = cursor.fetchone()\n return Note(linha[0], linha[1], linha[2])\n \n def update(self, entry : Note):\n cursor = self.conn.cursor()\n cursor.execute(f\"UPDATE note SET title = '{entry.title}', content = '{entry.content}' WHERE id = {entry.id}\")\n self.conn.commit()\n\n def delete(self, note_id):\n cursor = self.conn.cursor()\n cursor.execute(f\"DELETE FROM note WHERE id = {note_id}\")\n self.conn.commit()\n","repo_name":"RaulRangelMB/TecWebProjeto1A","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"29823101426","text":"from unit import Unit, Race\nfrom cell import Cell\nfrom time import sleep\nimport sys\nimport curses\nimport cProfile\n\n\nclass Simulation:\n def __init__(self, input):\n self.input = input\n self.units = []\n self.elves = 0\n self.goblins = 0\n self.walls = []\n self.field = {}\n self.unit_order = None\n self.round = 0\n self.FPS = 1/25\n self.count = 0\n self.reboot = False\n self.elf_atk = 3\n self.screen = None\n self.outcome = 0\n\n def parse(self):\n self.columns = self.input.index(\"\\n\")\n input_rows = self.input.split('\\n')\n self.rows = len(input_rows)\n\n for y in range(self.rows):\n for x in range(self.columns):\n token = input_rows[y][x]\n occupier = None\n if token == \"E\":\n self.units.append((x, y))\n occupier = Unit((x, y), Race.elf)\n occupier.atk = self.elf_atk\n self.elves += 1\n if token == \"G\":\n self.units.append((x, y))\n occupier = Unit((x, y), Race.goblin)\n self.goblins += 1\n if token == \"#\":\n self.walls.append((x, y))\n occupier = token\n self.field[(x, y)] = Cell((x, y), occupier)\n\n def summary(self):\n output = \"\"\n hitpoints = 0\n for loc in self.units:\n hitpoints += self.unit_at(loc).hp\n winner = \"Elves\" if self.elves > self.goblins else \"Goblins\"\n output += \"Combat ends after \" + str(self.round) + \" full rounds\\n\"\n output += winner + \" win with \"\n output += str(hitpoints) + \" total hit points left\\n\"\n output += \"Outcome: \" + str(self.round) + \" * \"\n output += str(hitpoints) + \" = \" + str(hitpoints * self.round)+\"\\n\"\n output += \"Final attack power: \" + str(self.elf_atk) + \"\\n\"\n return output, hitpoints * self.round\n\n def dimensions(self):\n return (self.columns, self.rows)\n\n def unit_at(self, loc):\n if loc in self.units:\n return self.field.get(loc).occupier\n\n def get_units_in_contact(self, unit):\n contacts = {}\n for loc in self.get_adjacents(unit.loc):\n if loc in self.units:\n adjacent = self.field.get(loc)\n if adjacent.occupier.race != unit.race:\n contacts[loc] = adjacent\n return dict(sorted(contacts.items(),\n key=lambda k: (k[1].occupier.hp, k[1].loc[1], k[1].loc[0])))\n\n def wall_at(self, loc):\n return loc in self.walls\n\n def determine_order(self):\n self.unit_order = []\n for loc in sorted(self.units, key=lambda k: (k[1], k[0])):\n self.unit_order.append(self.field[loc].occupier)\n return self.unit_order\n\n def turn_order(self):\n return self.unit_order\n\n def get_adjacents(self, loc):\n (target_x, target_y) = loc\n points = ((target_x, target_y - 1),\n (target_x - 1, target_y),\n (target_x, target_y + 1),\n (target_x + 1, target_y))\n return [loc for loc in points if self.is_reachable(loc)]\n\n def is_reachable(self, loc):\n x, y = loc\n return not ((x < 0 or x >= self.columns) or (y < 0 or y >= self.rows))\n\n def is_occupied(self, loc):\n return loc in self.units or loc in self.walls\n\n def kill(self, unit):\n if not unit:\n return\n target = unit.loc\n self.units.remove(target)\n self.field[target] = Cell(target)\n if unit.race == Race.goblin:\n self.goblins -= 1\n else:\n self.elves -= 1\n if self.pt2:\n self.elf_atk += 1\n self.reboot = True\n\n def still_turns_to_play(self, rounds):\n return (rounds - self.round) != 0\n\n def find_targets(self, unit):\n return [x for x in self.turn_order() if x.is_alive() and x.race != unit.race]\n\n def find_ranges(self, unit, targets):\n ranges = set()\n for target in targets:\n for loc in self.get_adjacents(target.loc):\n if unit.loc == loc or not self.is_occupied(loc):\n ranges.add(loc)\n return ranges\n\n def find_reachable_targets(self, unit, targets):\n open = []\n closed = set()\n seen = []\n reachable = []\n shortest_distance = 9999\n\n open.append((unit.loc, 0, None))\n while open:\n target, dist, parent = open.pop(0)\n\n if dist > shortest_distance:\n continue\n\n if target in targets:\n reachable.append((target, dist))\n shortest_distance = dist\n\n cell = (target, dist, parent)\n if cell not in closed:\n closed.add(cell)\n\n if target in seen:\n continue\n seen.append(target)\n\n if target != unit.loc and self.is_occupied(target):\n continue\n\n for loc in self.get_adjacents(target):\n open.append((loc, dist + 1, target))\n return reachable, closed\n\n def choose_best_path(self, closest, paths):\n (min_dist, chosen) = closest\n parents = [x for x in paths if x[0] == chosen and x[1] == min_dist]\n while min_dist > 1:\n min_dist -= 1\n new_parents = set()\n for _, _, p in parents:\n for target, dist, parent in paths:\n if target == p and dist == min_dist:\n new_parents.add((target, dist, parent))\n parents = new_parents\n return sorted(set(target for target, _, _ in parents), key=lambda k: (k[1], k[0])).pop(0)\n\n def find_closest_target(self, unit, targets):\n reachable_targets, paths = self.find_reachable_targets(unit, targets)\n if not reachable_targets:\n return None\n closest = self.choose_closest_target(reachable_targets)\n return self.choose_best_path(closest, paths)\n\n def choose_closest_target(self, reachable):\n min_dist = min(x[1] for x in reachable)\n min_reachable = sorted([x[0] for x in reachable if x[1] == min_dist],\n key=lambda k: (k[1], k[0]))\n return (min_dist, min_reachable[0])\n\n def play_turn(self, unit):\n if not unit.is_alive():\n return True\n\n targets = self.find_targets(unit)\n if not targets:\n return False\n\n ranges = self.find_ranges(unit, targets)\n if not ranges:\n return True\n\n # self.render(self.screen, unit.loc,[[ranges]])\n if unit.loc in ranges:\n chosen_target = unit.attack(self.get_units_in_contact(unit))\n casualty = unit.hit(chosen_target)\n if casualty:\n self.kill(casualty)\n return True\n\n chosen_target = self.find_closest_target(unit, ranges)\n if not chosen_target:\n return True\n\n contacts = None\n if chosen_target:\n self.units.remove(unit.loc)\n self.field[unit.loc] = Cell(unit.loc)\n unit.loc = chosen_target\n self.field[unit.loc] = Cell(unit.loc, unit)\n self.units.append(unit.loc)\n contacts = self.get_units_in_contact(unit)\n if contacts:\n chosen_target = unit.attack(contacts)\n casualty = unit.hit(chosen_target)\n if casualty:\n self.kill(casualty)\n return True\n\n def move_unit(self, unit, destination):\n self.units.remove(unit.loc)\n self.field[unit.loc] = Cell(unit.loc)\n unit.loc = destination\n self.field[unit.loc] = Cell(unit.loc, unit)\n self.units.append(unit.loc)\n return unit\n \n def resolve_combat(self, screen, rounds):\n self.init_screen(screen)\n self.reboot = False\n while self.still_turns_to_play(rounds):\n self.render()\n for unit in self.determine_order():\n if not self.play_turn(unit):\n summary, self.outcome = self.summary()\n screen.addstr(summary, curses.color_pair(5) )\n screen.addstr(\"HIT ANY KEY TO CONTINUE\")\n screen.getkey()\n return False\n if self.reboot:\n return True\n sleep(self.FPS) \n self.round += 1\n\n def reset_battle(self):\n self.units = []\n self.elves = 0\n self.goblins = 0\n self.walls = []\n self.field = {}\n self.round = 0\n self.reboot = False\n self.parse()\n \n def render(self, current=None, lists=[]):\n output = \"\"\n flat_list = [item for sublist in lists for sublist2 in sublist for item in sublist2]\n output += \"Round: \" + str(self.round) + \"\\tElves:\" + str(self.elves)\n output += \", Goblins:\" + str(self.goblins)\n output += \"\\t\" + str(self.count)\n self.screen.addstr(0,0, output)\n output = \"Elf attack power: \" + str(self.elf_atk)\n if current:\n output += \"\\tCurrent unit: \" + str(current) + \"\\n\"\n self.screen.addstr(1,0, output)\n for y in range(self.rows):\n hits = []\n for x in range(self.columns):\n colour = 4\n if (x, y) in flat_list or (x, y) == current:\n token = \"*\"\n colour = 5\n else:\n token = self.field[(x, y)]\n if isinstance(token.occupier, Unit):\n colour = 2 + int(token.occupier.race)\n self.screen.addch(y+2, x, ord(str(token)), curses.color_pair(colour))\n if (x, y) in self.units:\n unit = self.unit_at((x, y))\n hits.append(unit.race.name+\"(\"+str(unit.hp)+\")\")\n output = \"\\t\\t\" + \" \".join(hits) + \"\\n\"\n self.screen.addstr(y+2, x, output)\n self.screen.refresh()\n self.count += 1\n return output\n \n def init_screen(self, screen):\n self.screen = screen\n self.screen.clear()\n curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)\n curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\n def main(self, rounds, pt2=False):\n self.pt2 = pt2\n if pt2:\n self.FPS = 0\n self.elf_atk = 4\n self.parse()\n while curses.wrapper(self.resolve_combat, rounds):\n self.reset_battle()\n pass\n\n\nif __name__ == \"__main__\":\n file = sys.argv[1]\n if len(sys.argv) > 2:\n max_rounds = int(sys.argv[2])\n else:\n max_rounds = -1\n with open(file, 'r') as myfile:\n input = myfile.read()\n sim = Simulation(input)\n print(\"Part 1:\")\n sim.main(max_rounds, False)\n print(\"Outcome: \", sim.outcome)\n \n print(\"Part 2:\")\n sim = Simulation(input)\n sim.main(max_rounds, True)\n print(\"Outcome: \", sim.outcome)\n # cProfile.run('sim.main(max_rounds, False)')\n","repo_name":"chrisesharp/aoc-2018","sub_path":"day15/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":11386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"7617616796","text":"from logging import root\nfrom django.shortcuts import render, get_object_or_404\nfrom django.conf import settings\nfrom bookings.models import Booking\nfrom rooms.models import Room\nfrom guest_reservations.models import GuestReservationList, ReservationItem\n\n\n# payment process with flutterwave payment parameters\ndef payment_process(request, booking_id):\n publicKey = settings.FLUTTERWAVE_TEST_PUBLIC_KEY\n booking = get_object_or_404(Booking, id=booking_id)\n customer_email = booking.guest_email\n customer_phone = booking.guest_telephone\n amount = booking.amount\n tx_ref = \"lSriN9302\" + str(booking.id)\n return render(request, 'payment/payment_process.html',\n {\n 'publicKey': publicKey,\n 'customer_email': customer_email,\n 'customer_phone': customer_phone,\n 'amount': amount,\n 'tx_ref': tx_ref,\n 'id':booking.id,\n }\n )\n\ndef payment_successful(request, id):\n booking = get_object_or_404(Booking, id=id)\n booking.paid = True\n booking.save()\n \n #process of adding booking reservation list here###\n booking_id = request.session['booking_id_data']\n reservation_list = get_object_or_404(GuestReservationList, guest=request.user)\n booking = get_object_or_404(Booking, id=booking_id)\n reservation_item = ReservationItem.objects.create(reservation_list=reservation_list, booking=booking)\n reservation_item.save()\n ######\n \n room_id = request.session['room_id_data']\n room = get_object_or_404(Room, id=room_id)\n room.is_available = False\n room.is_booked = True\n room.save() # saving new status of the room\n \n # deleting session data\n # del request.session[\"check_in_data\"] .................to be used in hotel services app\n # del request.session[\"check_out_data\"] ................ to be used in hotel services app\n del request.session[\"room_type_data\"]\n del request.session['room_id_data']\n # del request.session['booking_id_data']\n \n return render(request, 'payment/payment_successful.html', {'id':id})\n\ndef payment_failed(request):\n return render(request, 'payment/payment_failed.html')","repo_name":"Princeigwe/LeisureInn","sub_path":"payments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"25169283155","text":"from handlers.input_handler import input_message\nfrom controller.docker_controller import show_docker_information, show_docker_usage\nfrom genetic_algorithm import genetic_algorithm\nfrom manual_stress_test import manual_stress_test\nfrom dotenv import load_dotenv\n\n\nif __name__ == \"__main__\":\n\n load_dotenv()\n\n MENU = -1\n MENU_LIST = {\n \"1\": (\"Show docker information\", show_docker_information),\n \"2\": (\"Show running docker container status\", show_docker_usage),\n \"3\": (\"Run genetic algorithm\", genetic_algorithm),\n \"4\": (\"Run manual stress test\", manual_stress_test),\n \"5\": (\"Exit\", exit),\n }\n\n while MENU != len(MENU_LIST):\n MENU = -1\n\n input_message(withInput=False)\n print(\"Main Menu\")\n for index in MENU_LIST.keys():\n print(index + \". \" + MENU_LIST[index][0])\n\n while MENU < 1 or MENU > len(MENU_LIST):\n try:\n MENU = int(input(\">> \"))\n except ValueError:\n MENU = -1\n input_message(withInput=False)\n\n MENU_LIST.get(str(MENU))[1]()\n input_message(withEnter=False)\n","repo_name":"WU19-1/simple_genetic_algorithm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"15696184538","text":"# 1493. Longest Subarray of 1's After Deleting One Element\n# User Accepted:3497\n# User Tried:3867\n# Total Accepted:3616\n# Total Submissions:6849\n# Difficulty:Medium\n# Given a binary array nums, you should delete one element from it.\n# Return the size of the longest non-empty subarray containing only 1's in the resulting array.\n# Return 0 if there is no such subarray.\n\n# Example 1:\n# Input: nums = [1,1,0,1]\n# Output: 3\n# Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\n\n# Example 2:\n# Input: nums = [0,1,1,1,0,1,1,0,1]\n# Output: 5\n# Explanation: After deleting the number in position 4, \n# [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\n\n# Example 3:\n# Input: nums = [1,1,1]\n# Output: 2\n# Explanation: You must delete one element.\n\n# Example 4:\n# Input: nums = [1,1,0,0,1,1,1,0,1]\n# Output: 4\n\n# Example 5:\n# Input: nums = [0,0,0]\n# Output: 0\n \n# Constraints:\n# 1 <= nums.length <= 10^5\n# nums[i] is either 0 or 1.\n\n# TLE\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n if sum(nums) == len(nums):\n return sum(nums) - 1\n \n def helper(nums):\n cnt = 0\n res = 0\n for i in range(len(nums)):\n if nums[i] == 1:\n cnt += 1\n if nums[i] == 0:\n res = max(res, cnt)\n cnt = 0\n res = max(res, cnt)\n return res\n \n t = 0\n r = 0\n fwd = [0] * len(nums)\n bwd = [0] * len(nums)\n leave = [0] * len(nums)\n \n for i in range(len(nums)): \n fwd[i] = helper(nums[:i])\n bwd[i] = helper(nums[i+1:])\n leave[i] = helper(nums[:i]+nums[i+1:])\n \n res = [0] * len(nums)\n if nums[0] == 0:\n res[0] = bwd[0]\n if nums[-1] == 0:\n res[0] = fwd[0]\n \n tmp = [1] * len(nums)\n if nums[0] == 0 and nums[1] == 0:\n tmp[0] = 0\n if nums[-1] == 0 and nums[-2] == 0:\n tmp[0] = 0\n for i in range(1, len(nums)-1):\n if (nums[i] == 0 and nums[i+1] == 0) or (nums[i] == 0 and nums[i-1] == 0):\n tmp[i] = 0\n \n # print(tmp)\n for i in range(1, len(nums)-1):\n if nums[i] == 0 and tmp[i]:\n res[i] = leave[i]\n elif nums[i] == 0:\n res[i] = max(fwd[i], bwd[i])\n if nums[i] == 1:\n res[i] = max(fwd[i], bwd[i])\n \n # for i in range(len(nums)):\n # res[i] *= tmp[i]\n \n # print(fwd, bwd, res)\n return max(res)","repo_name":"WatsonWangZh/AlgorithmPractice","sub_path":"Contest/LeetCode/BiweeklyContest29/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"80"} +{"seq_id":"36834586433","text":"import bge\nimport random\nimport time\nimport math\n\n# Moves an item to random location on x and y\n# and to the z location on the ground\ndef moveItemRandToGround(obj):\n # Assumption: The ground is below the object \n radius = 125\n degrees = random.randint(0, 360)\n radians = math.radians(degrees)\n valuex = math.fabs(math.ceil(math.sin(radians)*radius))\n valuey = math.fabs(math.ceil(math.cos(radians)*radius))\n \n obj.worldPosition = [random.randint(-valuex, valuex), random.randint(-valuey, valuey), 100]\n colobj, point, normal = obj.rayCast([obj.position[0], obj.position[1], -100], None, 200)\n while (colobj is None or colobj.name != \"Grid\"):\n obj.worldPosition = [random.randint(-valuex, valuex), random.randint(-valuey, valuey), 100]\n colobj, point, normal = obj.rayCast([obj.position[0], obj.position[1], -100], None, 200)\n\n obj.worldPosition[2] = point[2] + 2\n\ndef moveItemToGround(obj):\n colobj, point, normal = obj.rayCast([obj.position[0], obj.position[1], -100], None, 200)\n obj.worldPosition[2] = point[2] + 2\n\ndef spawnGun(obj):\n print(\"INFO: Spawning \" + obj)\n scene = bge.logic.getCurrentScene()\n createdObj = scene.addObject(obj, \"ItemSpawner\")\n moveItemRandToGround(createdObj)\n createdObj.suspendDynamics()\n\n\n","repo_name":"bchu007/CS179N","sub_path":"blender/logic/python/itemSpawn.py","file_name":"itemSpawn.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"71377444097","text":"\"\"\"\nffmpeg -i \"ENTRADA\" -i \"LEGENDA\" -c:v libx264 -crf 23 -preset ultrafast\n-c:a aac -b:a 320k -c:s srt -map v:0 -map a -map 1:0 -ss 00:00:00 -to 00:00:10 \"SAIDA\"\n\"\"\"\nimport os\nimport fnmatch\nimport sys\n\nif sys.platform == 'linux':\n comando_ffmpeg = 'ffmpeg'\nelse:\n comando_ffmpeg = r'ffmpeg\\ffmpeg.exe'\n\ncodec_video = '-c:v libx264'\ncrf = '-crf 23'\npreset = '-preset ultrafast'\ncodec_audio = '-c:a aac'\nbitrate_audio = '-b:a 320k'\ndebug = '-ss 00:00:00 -to 00:00:10'\n\ncaminho_origem = '/home/ivander/Downloads'\ncaminho_destino = '/home/ivander/Downloads/saida'\n\nfor root, directory, files in os.walk(caminho_origem):\n for file in files:\n if not fnmatch.fnmatch(file, '*.mp4'):\n continue\n caminho_completo = os.path.join(root, file)\n filename, fileext = os.path.splitext(caminho_origem)\n caminho_legenda = filename + '.srt'\n\n if os.path.isfile(caminho_legenda):\n input_legenda = f'-i \"{caminho_legenda}\"'\n map_legenda = '-c:s srt -map v:0 -map a -map 1:0'\n else:\n input_legenda = ''\n map_legenda = ''\n\n filename, fileext = os.path.splitext(file)\n\n arquivo_saida = f'{caminho_destino}/{filename}_novo{fileext}'\n\n comando = f'{comando_ffmpeg} -i \"{caminho_completo}\" {input_legenda} {codec_video} {crf} {preset}' \\\n f' {codec_audio} {bitrate_audio} {debug} {map_legenda} \"{arquivo_saida}\"'\n\n os.system(comando)\n","repo_name":"ivandersr/my-python-notebooks","sub_path":"oslibffmpeg/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"44434909742","text":"from selenium import webdriver\nfrom wcagcompatibility.rule_checker import RuleChecker\nfrom wcagcompatibility.utility import Utility\n\n\nclass TableHeaderChecker(RuleChecker):\n\n def __init__(self):\n self.table_width = 0\n self.headers_width = 0\n\n def check_rule(self, browser):\n \"\"\"Returns a tuple consists of compliant status (boolean) and tuple/array of messages (string) for non compliant status.\n Compliant status is true if all tables has header, false otherwise\"\"\"\n tables = browser.find_elements_by_tag_name('table')\n if tables:\n compliant = True\n messages = []\n for table in tables:\n compliant_message = self.check_table_header(table)\n compliant = compliant & compliant_message[0]\n if not compliant:\n messages.append(compliant_message[1])\n return compliant, messages\n else:\n return True, None\n\n def check_table_header(self, table):\n role = table.get_attribute('role')\n if role is not None and (role == 'presentation' or role == 'none'):\n return True, None\n else:\n aria_hidden = table.get_attribute('aria-hidden')\n if aria_hidden:\n return True, None\n\n #none of tables's role or aria-hidden attributes are compliant\n compliant_messages = self.check_both_scope_headers_ids(table)\n if not compliant_messages[0]:\n return compliant_messages\n else:\n compliant_messages = self.check_scopes(table)\n if compliant_messages[0]:\n return compliant_messages\n else:\n return self.check_headers_ids(table)\n\n def check_scopes(self, table):\n rows = table.find_element_by_xpath('/child::tr')\n \n pass\n\n def check_th_scope(self, cell):\n scope = cell.get_attribute('scope')\n colspan = cell.get_attribute('colspan')\n rowspan = cell.get_attribute('rowspan')\n message = Utility.get_message(cell)\n if scope:\n if scope == 'col' or scope == 'row':\n if colspan:\n message = Utility.add_message(message, self.get_scope_message(scope, 'colspan', colspan))\n return False, message\n elif rowspan:\n message = Utility.add_message(message, self.get_scope_message(scope, 'rowspan', rowspan))\n return False, message\n elif scope == 'colgroup':\n if rowspan:\n message = Utility.add_message(message, self.get_scope_message(scope, 'rowspan', rowspan))\n return False, message\n elif scope == 'rowgroup':\n if colspan:\n message = Utility.add_message(message, self.get_scope_message(scope, 'colspan', colspan))\n return False, message\n return True\n\n def get_scope_message(self, scope, incompatible_name, incompatible):\n return 'scope=={0} and {1}=={2}'.format(scope, incompatible_name, incompatible)\n\n def is_valid_cell(self, cell, left_cell, top_cell, cell_pos):\n if left_cell:\n if left_cell.tag_name == 'td':\n return cell.tag_name == 'td', self.get_invalid_cell_message(cell_pos, 'th', 'td', left_cell, top_cell)\n else: # left_cell.tag_name == 'th'\n if top_cell:\n if top_cell.tag_name == 'td':\n return cell.tag_name == 'td', self.get_invalid_cell_message(cell_pos, 'th', 'td', left_cell, top_cell)\n else: # top_cell.tag_name == 'th'\n return cell.tag_name == 'th', self.get_invalid_cell_message(cell_pos, 'td', 'th', left_cell, top_cell)\n else:\n return True, ''\n\n elif top_cell:\n if top_cell.tag_name == 'td':\n return cell.tag_name == 'td', self.get_invalid_cell_message(cell_pos, 'th', 'td', left_cell, top_cell)\n else: # top_cell.tag_name == 'th'\n if self.headers_width < self.table_width:\n return cell.tag_name == 'th', self.get_invalid_cell_message(cell_pos, 'td', 'th', left_cell, top_cell)\n else: # self.headers_width == self.table_width\n return True\n else: # top_cell == None, left_cell == None, cell == table_top_left_cell\n return cell.tag_name == 'th', self.get_invalid_cell_message(cell_pos, 'td', 'th', left_cell, top_cell)\n\n @staticmethod\n def get_invalid_cell_message(cell_pos, tag_is, tag_must, left_cell, top_cell):\n base_message = 'cell at [{0}, {1}] is {2}, must be {3}'.format(cell_pos[0], cell_pos[1], tag_is, tag_must)\n\n if left_cell:\n if top_cell:\n adjacent_message = 'left is {0}, top is {1}'.format(left_cell.tag_name, top_cell.tag_name)\n else:\n adjacent_message = 'left is {0}'.format(left_cell.tag_name)\n elif top_cell:\n adjacent_message = 'top is {0}'.format(top_cell.tag_name)\n else:\n adjacent_message = ''\n\n return base_message + ', ' + adjacent_message\n\n @staticmethod\n def get_cell_size(cell):\n colspan = cell.get_attribute('colspan')\n rowspan = cell.get_attribute('rowspan')\n width = 1\n height = 1\n if colspan:\n width = int(colspan)\n if rowspan:\n height = int(rowspan)\n return width, height\n\n def check_headers_ids(self, table):\n pass\n\n def check_both_scope_headers_ids(self, table):\n pass\n","repo_name":"Ali-Dorri/WCAG-Compatibility","sub_path":"wcagcompatibility/table_header_checker.py","file_name":"table_header_checker.py","file_ext":"py","file_size_in_byte":5677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"30378010855","text":"class Solution:\n def longestOnes(self, nums: List[int], k: int) -> int:\n # Reference: https://leetcode.com/problems/max-consecutive-ones-iii/solutions/247564/java-c-python-sliding-window/\n l = 0\n for r in range(len(nums)):\n k -= 1 - nums[r]\n if k < 0: # There are more than k zeros in sliding window\n k += 1 - nums[l]\n l += 1\n return r - l + 1\n","repo_name":"andy2167565/leetcode","sub_path":"Medium/1004_max-consecutive-ones-iii/max-consecutive-ones-iii.py","file_name":"max-consecutive-ones-iii.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"3024396162","text":"\"\"\"My first full blown cog that I wrote for this bot. Defines the filesCog class where all the commands are located. This cog revolves around file interaction, which is things like storing user tags,\n and hopefully soon, interacting with files and more.\n\"\"\"\n# TODO - Maybe just change filesCog to a tag cog if it gets too large?\n\nimport discord\nfrom discord.ext import commands\nfrom discord import Client\nimport json\n\nclass FilesCog:\n \"\"\"Used to define commands that interact with files. Currently, it's focused on tags, allowing for users to make tags, delete them, edit them, get info on them, and list all the tags.\"\"\"\n\n def __init__(self, client):\n \"\"\"Initializes everything.\"\"\"\n\n self.client = client\n\n with open(\"config.json\", \"r\") as my_file:\n\n try:\n data = json.load(my_file)\n self.ownerid = data[\"Owner ID\"]\n\n except Exception as e:\n print(\"An error has occured. {0}\".format(e))\n my_file.close()\n\n self.server_id_list = []\n\n # Gathers all the servers the bot is in to create a dictionary out of the string values.\n for server in self.client.servers:\n\n self.server_id_list.append(server.id)\n\n self.tagdicts = []\n\n for server in self.client.servers:\n try:\n with open(\"cogs/tags/{0}.json\".format(server.id), \"r\") as mytags:\n try:\n data = json.load(mytags)\n except ValueError:\n data = {}\n self.tagdicts.append( {server.id: data} )\n\n except FileNotFoundError:\n with open(\"cogs/tags/{0}.json\".format(server.id), \"a+\") as mytags:\n print(\"New tags file created: {0}\".format(server.id))\n self.tagdicts.append( {server.id: None} )\n\n except Exception as e:\n print(\"An error has occured. {0}\".format(e))\n continue\n\n print(\"Total of {0} tag dictionaries loaded.\".format(len(self.server_id_list)), self.server_id_list)\n\n # pass_context allows for ctx to be used in functions\n # invoke_without_command allows for the tag command to be called by itself and not call itself when other subcommands are called.\n # @commands.group(pass_context=True, invoke_without_command=True)\n @commands.command(pass_context=True)\n async def tag(self, ctx, name):\n \"\"\"\n Master command for the tag group of commands.\n Checks for a passed tag name value and subcommand. If a tag name is passed, it will print the tag.\n If a subcommand is passed, then nothing here will run.\n \"\"\"\n\n workingdictionary = None\n for counter, value in enumerate(self.tagdicts):\n if ctx.message.server.id in value:\n workingdictionary = value\n workingid = ctx.message.server.id\n\n try:\n await self.client.say(workingdictionary[workingid][name][\"content\"])\n except KeyError:\n print(\"That tag does not exist!\")\n\n # @tag.command(pass_context=True)\n @commands.command(pass_context=True)\n async def tagadd(self, ctx, name: str, *, contents: str):\n \"\"\"Subcommand allowing for the user to add new tags.\"\"\"\n\n workingdictionary = None\n\n for counter, value in enumerate(self.tagdicts):\n if ctx.message.server.id in value:\n workingdictionary = value\n workingid = ctx.message.server.id\n\n if workingdictionary[workingid] is None:\n data = {}\n workingdictionary[workingid] = {}\n\n newtag = {name: {\"content\": contents, \"authorid\": ctx.message.author.id,\"authorname\": \"{0}#{1}\".format(ctx.message.author.name, ctx.message.author.discriminator)}}\n data.update(newtag)\n\n elif name not in workingdictionary[workingid]:\n with open(\"cogs/tags/{0}.json\".format(ctx.message.server.id)) as mytags:\n try:\n data = json.load(mytags)\n except ValueError:\n data = {}\n except Exception as e:\n print(\"An error has occurred - {0}\".format(e))\n\n newtag = {name: {\"content\": contents, \"authorid\": ctx.message.author.id, \"authorname\": \"{0}#{1}\".format(ctx.message.author.name, ctx.message.author.discriminator)}}\n data.update(newtag)\n\n with open(\"cogs/tags/{0}.json\".format(ctx.message.server.id), \"w\") as mytags:\n json.dump(data, mytags, indent=2)\n\n workingdictionary[workingid][name] = {\"content\": contents, \"authorid\": ctx.message.author.id, \"authorname\": \"{0}#{1}\".format(ctx.message.author.name, ctx.message.author.discriminator)}\n\n await self.client.say(\"Tag with name **{0}** and content **{1}** has been created.\".format(name, contents))\n\n # @tag.command(pass_context=True)\n @commands.command(pass_context=True)\n async def tagdelete(self, ctx, name: str):\n \"\"\"Subcommand allowing for the user to delete their tags.\"\"\"\n\n workingdictionary = None\n\n for counter, value in enumerate(self.tagdicts):\n if ctx.message.server.id in value:\n workingdictionary = value\n workingid = ctx.message.server.id\n\n if ctx.message.author.id != workingdictionary[workingid][name][\"authorid\"]:\n if ctx.message.author.id == self.ownerid:\n pass\n else:\n await self.client.say(\"Sorry, you don't have sufficient permissions to use this command! Only the owner, **{0}** can.\".format(workingdictionary[workingid][name][\"authorname\"]))\n return\n\n try:\n with open(\"cogs/tags/{0}.json\".format(ctx.message.server.id)) as mytags:\n try:\n data = json.load(mytags)\n except ValueError:\n data = {}\n\n data.pop(name, None)\n\n with open(\"cogs/tags/{0}.json\".format(ctx.message.server.id), \"w\") as mytags:\n json.dump(data, mytags, indent=2)\n\n workingdictionary[workingid].pop(name, None)\n await self.client.say(\"Your tag **{0}** has been deleted.\".format(name))\n\n except KeyError:\n await self.client.say(\"That tag does not exist!\")\n\n # @tag.command(pass_context=True)\n @commands.command(pass_context=True)\n async def tagedit(self, ctx, name: str, *, newcontent: str):\n \"\"\"Used to edit an existing tag.\"\"\"\n\n workingdictionary = None\n\n for counter, value in enumerate(self.tagdicts):\n if ctx.message.server.id in value:\n workingdictionary = value\n workingid = ctx.message.server.id\n\n if ctx.message.author.id != workingdictionary[workingid][name][\"authorid\"]:\n if ctx.message.author.id == self.ownerid:\n pass\n else:\n await self.client.say(\"Sorry, you don't have sufficient permissions to use this command! Only the owner, **{0}** can.\".format(workingdictionary[workingid][name][\"authorname\"]))\n return\n\n try:\n\n with open(\"cogs/tags/{0}.json\".format(ctx.message.server.id)) as mytags:\n try:\n data = json.load(mytags)\n except ValueError:\n data = {}\n\n data[name][\"content\"] = newcontent\n\n with open(\"cogs/tags/{0}.json\".format(ctx.message.server.id), \"w\") as mytags:\n json.dump(data, mytags, indent=2)\n\n workingdictionary[workingid][name][\"content\"] = newcontent\n\n await self.client.say(\"Your tag **{0}** has had its contents changed to **{1}**\".format(name, newcontent))\n\n except KeyError:\n await self.client.say(\"That tag does not exist!\")\n\n # @tag.command(pass_context=True)\n @commands.command(pass_context=True)\n async def taglist(self, ctx):\n \"\"\"Lists all the current tags in a nice embed.\"\"\"\n\n workingdictionary = None\n\n for counter, value in enumerate(self.tagdicts):\n if ctx.message.server.id in value:\n workingdictionary = value\n workingid = ctx.message.server.id\n\n # Basically, a giant string will be sent in the embed.\n keystring = \"\"\n\n if workingdictionary[workingid] is None:\n keystring = \"No tags currently exist!\"\n elif len(workingdictionary[workingid]) == 0:\n keystring = \"No tags currently exist!\"\n else:\n for key in workingdictionary[workingid]:\n keystring += key\n keystring += \"\\n\"\n\n listembed = discord.Embed(\n description=\"List of the currently stored tags.\",\n color=14434903)\n\n listembed.title = \"Here Be Tags\"\n\n listembed.add_field(name=\"Tag list:\", value=keystring)\n\n await self.client.say(embed=listembed)\n\n # @tag.command(pass_context=True)\n @commands.command(pass_context=True)\n async def taginfo(self, ctx, name: str):\n \"\"\"Provides the user with information about the tag they pass in an embed\"\"\"\n\n workingdictionary = None\n\n for counter, value in enumerate(self.tagdicts):\n if ctx.message.server.id in value:\n workingdictionary = value\n workingid = ctx.message.server.id\n\n try:\n if name in workingdictionary[workingid]:\n infoembed = discord.Embed(color=14434903)\n\n infoembed.title = \"Information for tag: **{0}**\".format(name)\n\n infoembed.add_field(name=\"**Tag:**\", value=name)\n infoembed.add_field(name=\"**Contents:**\", value=workingdictionary[workingid][name][\"content\"], inline=False)\n infoembed.add_field(name=\"**Author:**\", value=workingdictionary[workingid][name][\"authorname\"])\n\n await self.client.say(embed=infoembed)\n\n except KeyError:\n await self.client.say(\"That tag does not exist!\")\n\n async def on_server_join(self, server):\n \"\"\"Event trigger to help with the bug of tags not working when the bot joins a server while running.\"\"\"\n\n try:\n with open(\"cogs/tags/{0}.json\".format(server.id)) as f:\n try:\n data = json.load(f)\n except ValueError:\n data = {}\n self.tagdicts.append( {server.id: data} )\n print(\"New server joined, but there's already an existing tag file. Tag file {0} has been loaded.\".format(server.id))\n\n except FileNotFoundError:\n with open(\"cogs/tags/{0}.json\".format(server.id), \"a+\") as f:\n print(\"New tags file created on server join: {0}\".format(server.id))\n self.tagdicts.append( {server.id: None} )\n\n except Exception as e:\n print(\"An error has occurred. {0}\".format(e))\n\n\n\ndef setup(client):\n client.add_cog(FilesCog(client))\n","repo_name":"Yuzu/Akizuki","sub_path":"main/cogs/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":11072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"37202037831","text":"\"\"\"A class responsible for handling the message clusters receieved from vehicles\n and analyzing them to notice misbehavior\"\"\"\n\nimport math\nimport csv\nimport os\nimport sys\n\nLOWER_BOUND = 0\nUPPER_BOUND = 75\n#A structure for adding all messages, the structure works as the follwing\n# {msg1_fingerprint : [msg1_car1, msg1_car2, msg1_car3], msg2_fingerprint : [msg2_car1, msg2_car2]}\nmessages = {}\nmisbehaving = []\n\ndef misbehaving_msgs():\n \"\"\"Function responsible for going through all messages and adding misbehaving ones to a list\"\"\"\n for key in messages:\n if detect_misbehavior(messages[key]):\n misbehaving.append(key)\n\ndef detect_misbehavior(msg_set):\n \"\"\"Function for determining if a message is suspicious\"\"\"\n for msg in msg_set:\n dist = distance([float(msg.get(\"receiveXPosCoords\")), float(msg.get(\"receiveYPosCoords\"))],\n [float(msg.get(\"xposCoords\")),float(msg.get(\"yposCoords\"))])\n transfer_time = int(msg.get(\"receiveTime\")) - int(msg.get(\"genDeltaTime\"))\n print(dist)\n print(transfer_time)\n if LOWER_BOUND <= dist/transfer_time <= UPPER_BOUND: # transfer time is too short/inconsistent to be used this way\n continue\n return True\n return False\n\n\n\ndef distance (pos1, pos2):\n \"\"\"Returns the distance between two positions\"\"\"\n return math.sqrt(pow((pos2[0] - pos1[0]),2) + pow((pos2[1]-pos1[1]),2))\n\ndef collect_messages(collection):\n \"\"\"Add things here\"\"\"\n for msg in collection:\n fingerprint = msg.get(\"fingerprint\")\n if messages.get(fingerprint):\n messages[fingerprint].append(msg)\n else:\n messages.update({fingerprint : [msg]})\n msg.get(\"fingerprint\")\n\ndef read_csv(filename): \n with open(filename, 'r') as file:\n reader = csv.DictReader(file)\n for row in reader:\n messages.setdefault(row[\"fingerprint\"],[]).append(row)\n\ndef load_data(directory): \n for f in os.listdir(directory):\n if f.endswith('.csv'):\n file_path = os.path.join(directory, f)\n read_csv(file_path)\n \ndef main(args):\n \"\"\"A main method responsible for handling Intrusion Detection on network level\"\"\"\n directory = args[1]\n load_data(directory) # populates messages\n misbehaving_msgs()\n print(misbehaving)\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"anembac/idsse","sub_path":"src/oldfiles/network_ids.py","file_name":"network_ids.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"35247647740","text":"from django import urls\nfrom rest_framework import urlpatterns as rf_urls\n\nfrom . import views as i_views\n\n\napp_name = \"inventory\"\n\n# api_chart_urls = [\n# urls.path(\"api/sourceitem/chartdata/\", i_views.APIChartDataView.as_view(), name=\"api_sourceitem_chartdata\"),\n# ]\n# api_chart_urls = rf_urls.format_suffix_patterns(api_chart_urls, allowed=['api', 'chartjs'])\n\nurlpatterns = [\n urls.path(\"api/saved_search/\", i_views.APISavedSearchView.as_view(), name=\"saved_search\"),\n\n urls.path(\n \"api/sourceitem/autocomplete/\", i_views.APISourceItemAutocompleteSearchView.as_view(),\n name=\"api_sourceitem_autocomplete\"),\n\n urls.path(\n \"api/sourceitem/chartdata//\", i_views.APIChartDataView.as_view(),\n name=\"api_sourceitem_chartdata\"),\n\n urls.path(\n \"api/sourceitem/orders/\", i_views.APISourceItemOrdersView.as_view(), name=\"api_sourceitem_orders\"),\n urls.path(\n \"api/sourceitem/quantity_adjustment/\", i_views.APISourceItemQuantityAdjustmentView.as_view(),\n name=\"api_sourceitem_quantity_adjustment\"),\n urls.path(\n \"api/sourceitem/wide_filter/\", i_views.APISourceItemWideFilterView.as_view(), name=\"api_sourceitem_widefilter\"),\n\n urls.path(\"reports/created_today/\", i_views.ReportsCreatedTodayView.as_view(), name=\"reports_created_today\"),\n urls.path(\"reports/packaging_costs/\", i_views.ReportsPackagingCostsView.as_view(), name=\"reports_packaging_costs\"),\n urls.path(\"reports/price_over_time/\", i_views.ReportsPriceOverTimeView.as_view(), name=\"reports_price_over_time\"),\n\n urls.path(\n \"saved_search/current_prices\", i_views.SearchCriteriaCurrentPricesView.as_view(),\n name=\"saved_search_current_prices\"),\n\n urls.path(\"sourceitem/mathcheck/\", i_views.SourceItemMathCheckView.as_view(), name=\"sourceitem_mathcheck\"),\n urls.path(\"sourceitem/orders/\", i_views.SourceItemOrdersView.as_view(), name=\"sourceitem_orders\"),\n urls.path(\n \"sourceitem/order////\",\n i_views.SourceItemOrderItemsView.as_view(), name=\"sourceitem_order_items_with_date\"),\n urls.path(\n \"sourceitem/order///\", i_views.SourceItemOrderItemsView.as_view(),\n name=\"sourceitem_order_items\"),\n urls.path(\"sourceitem/search/\", i_views.SourceItemSearchView.as_view(), name=\"sourceitem_search\"),\n urls.path(\"sourceitem/search/save\", i_views.SourceItemSaveSearchView.as_view(), name=\"sourceitem_save_search\"),\n urls.path(\"sourceitem/stats/\", i_views.SourceItemStatsView.as_view(), name=\"sourceitem_stats\"),\n urls.path(\"sourceitem/create/\", i_views.SourceItemCreateView.as_view(), name=\"sourceitem_create\"),\n]\n","repo_name":"adamtorres/inventory","sub_path":"web/apps/inventory/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40048835149","text":"n=int(input())\nlist4=input().split()\na=[]\na.append(0)\nfor i in range(n):\n a.append(int(list4[i]))\nflag=0\nfor i in range(1,n+1):\n if i==a[a[a[i]]]:\n flag=1;\n break;\nif flag==1:\n print(\"YES\")\nelse:\n print(\"NO\")","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2817/60706/255227.py","file_name":"255227.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"15000267907","text":"import io\nimport json\nimport jenkins\n\nj = jenkins.Jenkins(\"http://127.0.0.1:8080\")\n\nwith io.open(\"/files/nodes.json\", \"r\", encoding=\"utf-8\") as f:\n nodes = json.load(f)\n\nfor key, data in nodes.iteritems():\n params = {\n \"port\": data[\"port\"],\n \"username\": data[\"username\"],\n \"credentialsId\": data[\"credid\"],\n \"host\": key\n }\n create = True\n for node in j.get_nodes():\n if node[\"name\"] == key:\n create = False\n if create:\n print(\"Creating Jenkins Slave Node: {}\".format(key))\n j.create_node(\n key,\n nodeDescription=data[\"description\"],\n remoteFS=data[\"remotefs\"],\n labels=data[\"labels\"],\n launcher=jenkins.LAUNCHER_SSH,\n launcher_params=params\n )\n","repo_name":"stanchan/docker-pipeline","sub_path":"jenkins-master/scripts/jenkins_add_nodes.py","file_name":"jenkins_add_nodes.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"10480882391","text":"from .base import TodoFunctionalTest\nfrom selenium import webdriver\n\nclass DeleteItem(TodoFunctionalTest):\n def delete_item(self,todo_text):\n row = self.find_table_row(todo_text)\n self.browser.find_element_by_tag_name('a').click()\n\n def test_can_delete_items(self):\n #Edith saved items to her list\n self.browser.get(self.live_server_url)\n self.enter_a_new_item('Buy peacock feathers')\n self.enter_a_new_item('Buy milk')\n\n #Edith wants to delete item and clicked on the delete\n self.delete_item('Buy peacock feathers')\n\n #Edith saw that the list updated and the item goes away.\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertIn('Buy milk', page_text)\n self.assertNotIn('Buy peacock feathers', page_text)\n","repo_name":"moepwintphyu1996/obeythetesitnggoat","sub_path":"superlists/functional_tests/delete_lists.py","file_name":"delete_lists.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"30117583702","text":"# coding: utf-8\nimport re\nimport os\nfrom setuptools import setup, find_packages\n\n\ndef fpath(name):\n return os.path.join(os.path.dirname(__file__), name)\n\n\ndef read(fname):\n return open(fpath(fname)).read()\n\n\nfile_text = read(fpath('{{ cookiecutter.name }}/__init__.py'))\n\n\ndef grep(attrname):\n pattern = r\"{0}\\W*=\\W*'([^']+)'\".format(attrname)\n strval, = re.findall(pattern, file_text)\n return strval\n\n\ndef get_data_files(*dirs):\n results = []\n for src_dir in dirs:\n for root, dirs, files in os.walk(src_dir):\n results.append((root, map(lambda f: root + \"/\" + f, files)))\n return results\n\n\nsetup(\n name='{{ cookiecutter.name }}',\n version=grep('__version__'),\n url='http://example.com/',\n author=grep('__author__'),\n author_email=grep('__email__'),\n description='Common libs of flask web develop',\n packages=find_packages(),\n include_package_data=True,\n data_files=get_data_files('templates'),\n zip_safe=False,\n platforms='any',\n install_requires=[\n ],\n entry_points={\n 'console_scripts': [\n '{{ cookiecutter.name }} = chiki.cli:main',\n ]\n },\n)\n","repo_name":"endsh/cookiecutter-chiki","sub_path":"{{cookiecutter.name}}/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"80"} +{"seq_id":"30927316836","text":"import scrapy\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom ..items import DonalwinItem\n\nclass DonalWinTweets(CrawlSpider):\n name = 'donaldwin' # the name of our Spider\n max_retries = 4\n start_urls = ['https://thedonald.win/?page=1']\n #start_urls = ['https://thedonald.win/p/469S7LG/weve-put-the-subreddit-in-restri/']\n base_url = 'https://thedonald.win/'\n \n\n rules = [Rule(LinkExtractor(allow = 'https://thedonald.win/?', deny = ['https://thedonald.win/new','https://thedonald.win/top','https://thedonald.win/rising']), callback= 'parse_filter_comments', follow=True)]\n \n\n '''\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.retries = {}\n\n def start_requests(self):\n yield scrapy.Request(\n self.start_urls[0],\n callback=self.parse,\n meta={\n 'handle_httpstatus_list': [302],\n },\n )\n\n def parse(self, response):\n # if response.status == 302:\n # retries = self.retries.setdefault(response.url, 0)\n # if retries < self.max_retries:\n # self.retries[response.url] += 1\n # yield response.request.replace(dont_filter=True)\n # else:\n # self.logger.error('%s still returns 302 responses after %s retries',response.url, retries) \n # return \n #print(len(start_urls))\n items = DonalwinItem()\n items_output = []\n print(\"1111111111111111111111111111111111111111111111111111111\")\n \n comments_url = response.css(\"div.actions a.comments::attr(href)\").getall()\n print(len(comments_url))\n #print(comments_url[])\n \n for comment_url in comments_url:\n comment_link_url = self.base_url+comment_url\n #output1 =yield scrapy.Request(response.urljoin(comment_url),callback = self.parse_comments, meta={'item':items})\n yield scrapy.Request(comment_link_url, callback=self.parse_comments)\n \n \n next_page = response.css(\"div.more a\").xpath(\"@href\").getall()\n print(next_page)\n print(\"*****************************************************************************\")\n if len(next_page) == 1:\n next_page_url = self.base_url + next_page[0]\n yield scrapy.Request(next_page_url, callback= self.parse)\n print(next_page_url)\n else:\n next_page_url = self.base_url + next_page[1]\n print(next_page_url)\n yield scrapy.Request(next_page_url,meta = {\n 'dont_redirect': True,\n 'handle_httpstatus_list': [302]\n }, callback= self.parse)\n print(\"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\") \n\n '''\n \n def parse_filter_comments(self, response):\n\n print(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n comment_page = response.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"more\", \" \" ))]//a').extract()\n if(not comment_page):\n post_title = response.css('a.title::text').extract()\n #print(post_title)\n post_href = response.css('a.title').xpath(\"@href\").extract()\n #print(post_href)\n #post_author = response.css('a.author::text').extract()\n post_author = response.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"since\", \" \" ))]//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"author\", \" \" ))]/text()').extract()\n #print(post_author)\n post_vote = response.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"count\", \" \" ))]//text()').extract()\n #print(post_vote)\n #post_body = response.css('div.content.text::text').extract()\n post_time = response.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"post\", \" \" ))]//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"timeago\", \" \" ))]').extract()\n #post_total_comments = response.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"total\", \" \" ))]//text()').extract().strip()\n post_total_comments = response.css(\"a.comments::text\").extract()\n post_comments_authors = response.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"comment\", \" \" ))]//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"author\", \" \" ))]').extract()\n #print(len(post_comments_authors))\n #comments_level1 = response.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"comment-list\", \" \" ))]//>//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"comment\", \" \" ))]').extract()\n #for comment_l1 in comments_level1:\n #\n comments = []\n \n for i in response.css('.comment-list > .comment:nth-child(n)').extract():\n #print(i)\n sel = scrapy.Selector(text = str(i))\n comment_author1 = sel.css('.author::text').extract()\n #print(comment_author1)\n child_author= sel.xpath('//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"child\", \" \" ))]//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"author\", \" \" ))]/text()').extract()\n #'//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"child\", \" \" ))]//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"child\", \" \" ))]//*[contains(concat( \" \", @class, \" \" ), concat( \" \", \"body\", \" \" ))]'\n #print(child_author)\n post_i = sel.css('.comment .body').extract()\n #print(post_i)\n \n for pp in post_i:\n #print(pp)\n sel2 = scrapy.Selector(text = str(pp))\n comment_author = sel2.css('a.author::text').extract()\n #print(comment_author)\n comment_parent = \"\"\n #print(child_author)\n if(len(comment_author) == 0):\n break\n if(comment_author[0] in child_author):\n #print(\"###########################it is a child########################################\")\n comment_parent = comment_author1[0]\n #print(\"parent =\" + comment_parent)\n \n comment_content = sel2.css('p').extract()\n #print(comment_content)\n comment_point = sel2.css('.points::text').extract()\n #print(comment_point)\n comment_time = sel2.css('.timeago').extract()\n #print(comment_time)\n comments.append([{\n 'comment_author' : comment_author,\n 'comment_parent' : comment_parent,\n 'comment_content' : comment_content,\n 'comment_time' : comment_time,\n 'comment_point' : comment_point,\n }]\n )\n #print(\"EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\") \n items = DonalwinItem() \n items['post_1title'] = post_title\n items['post_2href'] = post_href\n items['post_3author'] = post_author\n items['post_4vote'] = post_vote\n items['post_5time'] = post_time\n items['post_6total_comments'] = post_total_comments\n items['post_7comments'] = comments\n # #print(items)\n\n yield items\n # yield{\n # 'post_1title' : post_title,\n # 'post_2href' : post_href,\n # 'post_3author' : post_author,\n # 'post_4vote' : post_vote,\n # 'post_5time' : post_time,\n # 'post_6comments' : comments,\n # }\n else:\n print(response.url) \n","repo_name":"FTB-B/ScrapAWebSite","sub_path":"backup2_works_usingcrawler.py","file_name":"backup2_works_usingcrawler.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"69835009220","text":"import sys\nsys.stdin = open(\"input.txt\", \"rt\")\n\nimport time\nimport math\n\n# 1 2 3 4해서\n\n# 순열 완전탐색\ndef dfs(v):\n st = time.time()\n global sum\n if v>=n:\n # 여기서 합을 구하기\n for i in range(1,n-1):\n sum+=ref[i]*arr[i]\n if sum>=m:\n sum=0\n return\n sum+=arr[0]+arr[n-1]\n if sum==m:\n for x in arr:\n print(x, end=\" \")\n print()\n print(\"time : \", time.time()-st)\n sys.exit(0)\n sum=0\n return\n else:\n for i in range(1, n+1):\n if chk[i]==0:\n arr[v]=i\n chk[i]=1\n dfs(v+1)\n chk[i]=0\n\nif __name__ == \"__main__\":\n start = time.time()\n n, m = map(int, input().split())\n sum=0\n chk = [0]*(n+1)\n arr = [0]*n\n ref = [1]*n\n for i in range(1, n-1):\n ref[i]=int(math.factorial(n-1)/(math.factorial(i)*math.factorial(n-1-i)))\n dfs(0)\n print(\"time : \", time.time()-start)","repo_name":"fundhaa/coding_study","sub_path":"6-9.수열추측하기.py","file_name":"6-9.수열추측하기.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"37631845942","text":"import sadface.sadface as sadf\n\n\nclass DocumentAnnotator:\n\n def annotate_claims(self, claims):\n\n sadf.config.set_location(r\"C:\\Users\\ROSSA\\PycharmProjects\\pickaxe\\etc\\pickaxe.cfg\")\n sadf.config.load()\n sadf.sd = sadf.init()\n\n sadf.set_title(\"Pickaxe\")\n sadf.add_notes(\"Claim detection\")\n sadf.set_description(\"Pickaxe essay_corpus_results\")\n\n for claim in claims:\n con = str(claim)\n sadf.add_atom(con)\n #sadf.add_atom_metadata()\n\n print(sadf.prettyprint())\n jsonData = sadf.export_json()\n with open(r\"C:\\Users\\ROSSA\\PycharmProjects\\pickaxe\\output\\sadface.json\", \"w\") as jsonFile:\n jsonFile.write(jsonData)\n\n\nif __name__ == '__main__':\n main = DocumentAnnotator()\n main.annotate_claims(['above all', 'accordingly', 'actually', 'admittedly', 'after', 'after all', 'after that',\n 'afterwards', 'again',\n 'all in all', 'all the same', 'also', 'alternatively', 'although',\n 'always assuming that', 'anyway', 'as', 'as a consequence', 'as a corollary',\n 'as a result', 'as long as', 'as soon as', 'as well', 'at any rate', 'at first',\n 'at first blush', 'at first sight', 'at first view',\n 'at the moment when', 'at the outset', 'at the same time', 'because', 'before', 'but',\n 'by comparison', 'by contrast'])\n","repo_name":"rossahq/pickaxe","sub_path":"sadfaceTools/documentAnnotator.py","file_name":"documentAnnotator.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"39969915840","text":"import mysql.connector\n\n# 连接到数据库\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\", # 替换为你的用户名\n password=\"zhupx780512\", # 替换为你的密码\n database=\"mydatabase\" # 替换为你的数据库名\n)\n\n# 创建一个游标\nmycursor = mydb.cursor()\n\n# 创建一个新表\n# mycursor.execute(\"\"\"\n# CREATE TABLE customers (\n# id INT AUTO_INCREMENT PRIMARY KEY,\n# name VARCHAR(255),\n# address VARCHAR(255)\n# )\n# \"\"\")\n\nsql = \"INSERT INTO customers (name, address) VALUES (%s, %s)\"\nval = [\n ('Peter', 'Lowstreet 4'),\n ('Amy', 'Apple st 652'),\n ('Hannah', 'Mountain 21'),\n ('Michael', 'Valley 345'),\n ('Sandy', 'Ocean blvd 2'),\n ('Betty', 'Green Grass 1'),\n ('Richard', 'Sky st 331'),\n ('Susan', 'One way 98'),\n ('Vicky', 'Yellow Garden 2'),\n ('Ben', 'Park Lane 38'),\n ('William', 'Central st 954'),\n ('Chuck', 'Main Road 989'),\n ('Viola', 'Sideway 1633')\n]\n\nmycursor.executemany(sql, val)\n\nmydb.commit()\n\n","repo_name":"OOXXXX/PythonFile","sub_path":"SQL_test1/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"24380881816","text":"#!/usr/bin/env python3\nimport sys\nimport math\nfrom numpy import *\nfrom glfw.GLFW import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\n\nviewer = [0.0, 0.0, 10.0]\nviewing_dir = [0.0, 0.0, -10.0] \nup = [0.0, 1.0, 0.0]\nview_point = [0 for i in range(3)]\nfirst_mouse = True\n\ntheta = 0.0\nphi = 0.0\npix2angle = 1.0\n\nleft_mouse_button_pressed = 0\nright_mouse_button_pressed = 0\n\nmouse_x_pos_old = 0\ndelta_x = 0\n\nmouse_y_pos_old = 0\ndelta_y = 0\n\nscale = 1.0\npos = (0.0, 0.0)\nR = 10.0\nspace_pressed = 0\n\ndef startup():\n update_viewport(None, 400, 400)\n glClearColor(0.0, 0.0, 0.0, 1.0)\n glEnable(GL_DEPTH_TEST)\n\n\ndef shutdown():\n pass\n\n\ndef axes():\n glBegin(GL_LINES)\n\n glColor3f(1.0, 0.0, 0.0)\n glVertex3f(-5.0, 0.0, 0.0)\n glVertex3f(5.0, 0.0, 0.0)\n\n glColor3f(0.0, 1.0, 0.0)\n glVertex3f(0.0, -5.0, 0.0)\n glVertex3f(0.0, 5.0, 0.0)\n\n glColor3f(0.0, 0.0, 1.0)\n glVertex3f(0.0, 0.0, -5.0)\n glVertex3f(0.0, 0.0, 5.0)\n\n glEnd()\n\n\ndef example_object():\n glColor3f(1.0, 1.0, 1.0)\n\n quadric = gluNewQuadric()\n gluQuadricDrawStyle(quadric, GLU_LINE)\n glRotatef(90, 1.0, 0.0, 0.0)\n glRotatef(-90, 0.0, 1.0, 0.0)\n\n gluSphere(quadric, 1.5, 10, 10)\n\n glTranslatef(0.0, 0.0, 1.1)\n gluCylinder(quadric, 1.0, 1.5, 1.5, 10, 5)\n glTranslatef(0.0, 0.0, -1.1)\n\n glTranslatef(0.0, 0.0, -2.6)\n gluCylinder(quadric, 0.0, 1.0, 1.5, 10, 5)\n glTranslatef(0.0, 0.0, 2.6)\n\n glRotatef(90, 1.0, 0.0, 1.0)\n glTranslatef(0.0, 0.0, 1.5)\n gluCylinder(quadric, 0.1, 0.0, 1.0, 5, 5)\n glTranslatef(0.0, 0.0, -1.5)\n glRotatef(-90, 1.0, 0.0, 1.0)\n\n glRotatef(-90, 1.0, 0.0, 1.0)\n glTranslatef(0.0, 0.0, 1.5)\n gluCylinder(quadric, 0.1, 0.0, 1.0, 5, 5)\n glTranslatef(0.0, 0.0, -1.5)\n glRotatef(90, 1.0, 0.0, 1.0)\n\n glRotatef(90, 0.0, 1.0, 0.0)\n glRotatef(-90, 1.0, 0.0, 0.0)\n gluDeleteQuadric(quadric)\n\n\ndef render(time):\n global theta\n global phi\n global scale\n global pos\n global R\n global space_pressed\n global viewer\n global viewing_dir\n global up\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glLoadIdentity()\n #Funckja gluLookAt wykorzystywana do realizacji zadań od 3.0 do 4.5.\n #gluLookAt(viewer[0], viewer[1], viewer[2], 0.0, 0.0, 0.0, up[0], up[1], up[2])\n #Funckja gluLookAt wykorzystywana do realizacji zadania na 5.0.\n gluLookAt(viewer[0], viewer[1], viewer[2], viewer[0]+viewing_dir[0], viewer[1]+viewing_dir[1], viewer[2]+viewing_dir[2], up[0], up[1], up[2])\n\n #Obrót wokół osi Y\n '''if left_mouse_button_pressed:\n theta += delta_x * pix2angle\n\n glRotatef(theta, 0.0, 1.0, 0.0)'''\n #Obrót wokół osi X - Zadanie na 3.0\n '''if left_mouse_button_pressed:\n phi += delta_y * pix2angle\n glRotatef(phi, 1.0, 0.0, 0.0)'''\n #Obrót wokół osi X i Y.\n '''if left_mouse_button_pressed:\n theta += delta_x * pix2angle\n phi += delta_y * pix2angle\n\n glRotatef(theta, 0.0, 1.0, 0.0)\n glRotatef(phi, 1.0, 0.0, 0.0)'''\n\n #Przeskalowanie obrazu po wciśnięciu prawego przycisku myszy - Zadanie na 3.5\n '''if right_mouse_button_pressed:\n if (pos[0] > 200 and pos[1] < 200) or (pos[0] < 200 and pos[1] < 200):\n scale += 0.01\n else:\n scale -= 0.01\n \n glScalef(scale, scale, scale)'''\n #Zadanie na 4.0\n '''if left_mouse_button_pressed:\n theta += delta_x * pix2angle * 0.005\n phi += delta_y * pix2angle * 0.005\n \n viewer[0] = R * math.cos(theta) * math.cos(phi)\n viewer[1] = R * math.sin(phi)\n viewer[2] = R * math.sin(theta) * math.cos(phi)\n\n if right_mouse_button_pressed:\n if (pos[0] > 200 and pos[1] < 200) or (pos[0] < 200 and pos[1] < 200):\n R += 0.5\n else:\n R -= 0.5'''\n #Zadanie na 4.5 - dodanie poprawności przejść kamery wokół obiektu i wprowadzienie ograniczenia w zakresie przybliżania/oddalania kamery\n '''if left_mouse_button_pressed:\n theta += delta_x * pix2angle * 0.005\n phi += delta_y * pix2angle * 0.005\n theta = theta %(2*math.pi)\n phi = phi %(2*math.pi)\n if phi >= 0.5*math.pi and phi <= 1.5*math.pi:\n up[1] = -1.0\n else: \n up[1] = 1.0\n\n viewer[0] = R * math.cos(theta) * math.cos(phi)\n viewer[1] = R * math.sin(phi)\n viewer[2] = R * math.sin(theta) * math.cos(phi)\n \n if right_mouse_button_pressed:\n \n if (pos[0] > 200 and pos[1] < 200) or (pos[0] < 200 and pos[1] < 200):\n if R >= 4.0:\n R -= 0.1\n else:\n if R <= 25.0:\n R += 0.1'''\n #Zadanie na 4.5 - wprowadzenie możliwości przełączania między trybem obracania obiektu i trybem poruszania kamerą za pomocą naciśnięcia spacji \n '''if space_pressed == 0:\n if left_mouse_button_pressed:\n theta += delta_x * pix2angle\n phi += delta_y * pix2angle\n \n if right_mouse_button_pressed:\n if (pos[0] > 200 and pos[1] < 200) or (pos[0] < 200 and pos[1] < 200):\n scale += 0.01\n else:\n scale -= 0.01\n glRotatef(theta, 0.0, 1.0, 0.0)\n glRotatef(phi, 1.0, 0.0, 0.0) \n glScalef(scale, scale, scale)\n else:\n if left_mouse_button_pressed:\n theta += delta_x * pix2angle * 0.005\n phi += delta_y * pix2angle * 0.005\n theta = theta %(2*math.pi)\n phi = phi %(2*math.pi)\n if phi >= 0.5*math.pi and phi <= 1.5*math.pi:\n up[1] = -1.0\n else: \n up[1] = 1.0\n viewer[0] = R * math.cos(theta) * math.cos(phi)\n viewer[1] = R * math.sin(phi)\n viewer[2] = R * math.sin(theta) * math.cos(phi)\n\n if right_mouse_button_pressed:\n \n if (pos[0] > 200 and pos[1] < 200) or (pos[0] < 200 and pos[1] < 200):\n if R >= 4.0:\n R -= 0.1\n else:\n if R <= 25.0:\n R += 0.1'''\n \n axes()\n example_object()\n\n glFlush()\n\n\ndef update_viewport(window, width, height):\n global pix2angle\n pix2angle = 360.0 / width\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n\n gluPerspective(70, 1.0, 0.1, 300.0)\n\n if width <= height:\n glViewport(0, int((height - width) / 2), width, width)\n else:\n glViewport(int((width - height) / 2), 0, height, height)\n\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n\ndef keyboard_key_callback(window, key, scancode, action, mods):\n global space_pressed\n global viewer\n global viewing_dir\n global up\n\n cameraSpeed = 0.05\n if key == GLFW_KEY_ESCAPE and action == GLFW_PRESS:\n glfwSetWindowShouldClose(window, GLFW_TRUE)\n\n #Zadanie na 4.5 - klawisz Spacji przełącza tryb.\n if key == GLFW_KEY_SPACE and action == GLFW_PRESS:\n if space_pressed == 0:\n space_pressed = 1\n else:\n space_pressed = 0\n\n #Zadanie na 5.0 - W - ruch do przodu, A - ruch w lewo, S - ruch do tyłu, D - ruch w prawo \n if key == GLFW_KEY_W and action == GLFW_REPEAT:\n\n viewer[0] += cameraSpeed * viewing_dir[0]\n viewer[1] += cameraSpeed * viewing_dir[1]\n viewer[2] += cameraSpeed * viewing_dir[2]\n if key == GLFW_KEY_S and action == GLFW_REPEAT:\n viewer[0] -= cameraSpeed * viewing_dir[0]\n viewer[1] -= cameraSpeed * viewing_dir[1]\n viewer[2] -= cameraSpeed * viewing_dir[2]\n \n if key == GLFW_KEY_A and action == GLFW_REPEAT:\n cross_vector = cross(viewing_dir, up)\n length_vector = linalg.norm(cross_vector)\n viewer -= cameraSpeed * (cross_vector/length_vector)\n if key == GLFW_KEY_D and action == GLFW_REPEAT:\n cross_vector = cross(viewing_dir, up)\n length_vector = linalg.norm(cross_vector)\n viewer += cameraSpeed * (cross_vector/length_vector)\n \n\ndef mouse_motion_callback(window, x_pos, y_pos):\n global theta\n global phi\n global viewing_dir\n global first_mouse\n global delta_x\n global mouse_x_pos_old\n global delta_y\n global mouse_y_pos_old\n\n #Zadanie na 5.0 - początkowe ustawienie kursora myszy.\n if first_mouse:\n mouse_x_pos_old = 50 - x_pos\n mouse_y_pos_old = - 300 - y_pos\n first_mouse = False\n\n #Obliczenie różnicy położenia w poziomie dla aktualnej pozycji myszy. \n delta_x = x_pos - mouse_x_pos_old\n mouse_x_pos_old = x_pos\n \n #Obliczenie różnicy położenia w pionie dla aktualnej pozycji myszy - zadanie na 3.0. \n delta_y = y_pos - mouse_y_pos_old\n mouse_y_pos_old = y_pos\n\n #Zadanie na 5.0 - obsługa ruchu myszy\n theta += delta_x * pix2angle * 0.005\n phi += delta_y * pix2angle * 0.005\n\n theta = theta %(2*math.pi)\n phi = phi %(2*math.pi)\n \n\n view_point[0] = math.cos(theta) * math.cos(phi)\n view_point[1] = math.sin(phi)\n view_point[2] = math.sin(theta) * math.cos(phi)\n\n length_vector = linalg.norm(view_point)\n viewing_dir = view_point/length_vector\n\ndef mouse_button_callback(window, button, action, mods):\n global left_mouse_button_pressed\n global right_mouse_button_pressed\n\n if button == GLFW_MOUSE_BUTTON_LEFT and action == GLFW_PRESS:\n left_mouse_button_pressed = 1\n else:\n left_mouse_button_pressed = 0\n\n #Obsługa prawego przycisku myszy - zadanie na 3.5.\n if button == GLFW_MOUSE_BUTTON_RIGHT and action == GLFW_PRESS:\n right_mouse_button_pressed = 1\n else:\n right_mouse_button_pressed = 0\n\ndef main():\n global pos\n if not glfwInit():\n sys.exit(-1)\n\n window = glfwCreateWindow(400, 400, __file__, None, None)\n if not window:\n glfwTerminate()\n sys.exit(-1)\n\n glfwMakeContextCurrent(window)\n glfwSetFramebufferSizeCallback(window, update_viewport)\n glfwSetKeyCallback(window, keyboard_key_callback)\n glfwSetCursorPosCallback(window, mouse_motion_callback)\n glfwSetCursorPos(window, 200, 200)\n glfwSetMouseButtonCallback(window, mouse_button_callback)\n glfwSwapInterval(1)\n\n startup()\n while not glfwWindowShouldClose(window):\n render(glfwGetTime())\n pos = glfwGetCursorPos(window)\n glfwSwapBuffers(window)\n glfwPollEvents()\n shutdown()\n\n glfwTerminate()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"karolinakowalczyk/OpenGL-labs","sub_path":"lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":10362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38440207171","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport itertools\nfrom qiskit.compiler import transpile\nfrom qiskit import(QuantumCircuit, execute, Aer, BasicAer)\nfrom qiskit.visualization import plot_histogram\nfrom qiskit_optimization import QuadraticProgram\nfrom qiskit_optimization.algorithms import GroverOptimizer\nfrom docplex.mp.model import Model\nfrom qiskit.utils import algorithm_globals, QuantumInstance\nfrom qiskit.algorithms import NumPyMinimumEigensolver\nimport qiskit.algorithms\nfrom qiskit_optimization.algorithms import MinimumEigenOptimizer, RecursiveMinimumEigenOptimizer\nfrom qiskit import IBMQ\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# In[2]:\n\n\n## Logic for constructing the MQO model\n\ndef gen_sum(p1, savings):\n return sum([s for ((i,j),s) in savings if i==p1])\n\ndef calculate_wl(costs, epsilon):\n return max(costs)+epsilon\n\ndef calculate_wm(savings, wl):\n if not savings:\n return wl\n return wl + max([gen_sum(p1, savings) \n for p1 in list({i for ((i,j), s) in savings})])\n\ndef construct_model(model, queries, costs, savings):\n v = model.binary_var_list(len(costs))\n epsilon = 0.25\n wl= calculate_wl(costs, epsilon)\n wm= calculate_wm(savings, wl)\n \n El = model.sum(-1*(wl-costs[i])*v[i] \n for i in range(0, len(costs)))\n Em = model.sum(model.sum(wm*v[i]*v[j] \n for (i,j) in itertools.combinations(queries[k], 2)) \n for k in queries.keys())\n Es = model.sum(-s*v[i]*v[j] for ((i,j), s) in savings)\n return(El + Em + Es)\n\n\n# In[3]:\n\n\ndef solve_with_QAOA(qubo):\n qaoa_meas = qiskit.algorithms.QAOA(quantum_instance=Aer.get_backend('qasm_simulator'), initial_point=[0., 0.])\n qaoa = MinimumEigenOptimizer(qaoa_meas)\n qaoa_result = qaoa.solve(qubo)\n return qaoa_result, qaoa_meas.get_optimal_circuit()\n\n\n# In[4]:\n\n\n# Returns the queries, costs and savings collections for a small sample mqo instance\ndef get_sample_MQO_instance():\n ## Format: query id=key, list of associated query plans=value\n queries={0: [0,1,2], 1: [3,4], 2: [5,6,7]}\n\n ## Costs for each query plan. Format: index=plan, value=cost\n costs=[12,16,14,11,11,16,15,19]\n\n ## Cost savings for re-usable plans. Format: list of ((p1, p2), saving)\n ## where p1,p2 are overlapping plans for different queries\n savings=[((0,3), 40), ((0,4), 31),\n ((0,6), 4), ((0,7), 6),\n ((1,6), 2), ((1,7), 5)]\n return queries, costs, savings\n\n\n# In[5]:\n\n\n## Solves the MQO problem consisting of the given queries, costs and savings with various algorithms\ndef solve_MQO(queries, costs, savings): \n model = Model('docplex_model')\n\n model.minimize(construct_model(model, queries, costs, savings))\n\n qubo = QuadraticProgram()\n qubo.from_docplex(model)\n\n result_QAOA, QAOA_circuit = solve_with_QAOA(qubo)\n\n print(\"QAOA evaluation:\")\n print(result_QAOA)\n\n\n# In[6]:\n\n\nqueries, costs, savings = get_sample_MQO_instance()\nsolve_MQO(queries, costs, savings)\n\n","repo_name":"lfd/qsa_repro","sub_path":"expAnalysis/MQO/qiskit/mqo.py","file_name":"mqo.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"8710335291","text":"import sys\r\nread = lambda : sys.stdin.readline()\r\nanswers = []\r\nfor _ in range(int(read())):\r\n size, index = map(int, read().split(' '))\r\n que = list(map(int, read().split(' ')))\r\n count = 0\r\n while True:\r\n if(que[0] == max(que)):\r\n x = que.pop(0)\r\n count += 1\r\n if(index == 0):\r\n break\r\n else:\r\n index = int((index - 1) % len(que))\r\n else:\r\n que.append(que.pop(0))\r\n index = int((index - 1) % len(que))\r\n answers.append(count)\r\nfor answer in answers:\r\n print(answer)","repo_name":"2022-rescue-macbook/rescue-macbook-py","sub_path":"code/15702218.py3","file_name":"15702218.py3","file_ext":"py3","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17627989094","text":"from sklearn.linear_model import LogisticRegression\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.metrics import *\nfrom sklearn.model_selection import train_test_split, cross_val_score\nimport matplotlib.pyplot as plt\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\n\nrandom_state = 9999\n\n# 2020to2021\ntrain_df = pd.read_table(\"../FinalModel/team_match_rank_2020to2021.csv\", sep=\",\")\n\n# split data & response\nresponse = train_df[\"t1_win\"]\n\n# 官方 78,79\n# pagerank 76 77\n# 选手排名 80 81\noff_list = [4, 5]\nteam_rank = [6, 7]\nplayer_list = [8, 9]\n\nX_train_1, y_train_1 = train_df.iloc[0:296, off_list], response.iloc[0:296]\nX_train_2, y_train_2 = train_df.iloc[0:296, team_rank], response.iloc[0:296]\nX_train_3, y_train_3 = train_df.iloc[0:296, player_list], response.iloc[0:296]\nX_train_4, y_train_4 = train_df.iloc[0:296, off_list + team_rank], response.iloc[0:296]\nX_train_5, y_train_5 = train_df.iloc[0:296, off_list + player_list], response.iloc[0:296]\nX_train_6, y_train_6 = train_df.iloc[0:296, team_rank + player_list], response.iloc[0:296]\nX_train_7, y_train_7 = train_df.iloc[0:296, off_list + team_rank + player_list], response.iloc[0:296]\n\nX_list = [X_train_1, X_train_2, X_train_3, X_train_4, X_train_5, X_train_6, X_train_7]\ny_list = [y_train_1, y_train_2, y_train_3, y_train_4, y_train_5, y_train_6, y_train_7]\n\nX_test, y_test = train_df.iloc[296:, team_rank+player_list], response.iloc[296:]\n\nscaler = StandardScaler()\nstd_Xtrain = scaler.fit_transform(X_train_6)\n\nscaler = StandardScaler()\nstd_Xtest = scaler.fit_transform(X_test)\n\nlr_clf = LogisticRegression(\n random_state=random_state, penalty='l2', C=1.0)\n\nlr_clf.fit(std_Xtrain, y_train_2)\nscore2 = cross_val_score(lr_clf, std_Xtrain, y_train_2, cv=10)\n\n# 调参数\n# 1、AUC\n# y_pred_pa = lr_clf.predict_proba(X_test)\n# y_test_oh = label_binarize(y_test, classes=[0, 1])\n# print('调用函数auc:', roc_auc_score(y_test_oh, y_pred_pa, average='micro'))\npredictions = lr_clf.predict_proba(std_Xtest) # 每一类的概率\nfalse_positive_rate, recall, thresholds = roc_curve(y_test, predictions[:\n, 1])\nroc_auc = auc(false_positive_rate, recall)\nprint(\"AUC:\", roc_auc)\n\nplt.title('Receiver Operating Characteristic')\nplt.plot(false_positive_rate, recall, 'b', label='AUC = %0.2f' % roc_auc)\nplt.legend(loc='lower right')\nplt.plot([0, 1], [0, 1], 'r--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.0])\nplt.ylabel('Recall')\nplt.xlabel('Fall-out')\nplt.show()\n\n# 2、混淆矩阵\ny_pred = lr_clf.predict(std_Xtest)\n\n\n# for t in thresholds:\n# y_pred_new = []\n# print(t)\n# for y in predictions:\n# if y[0] > t:\n# y_pred_new.append(0)\n# else:\n# y_pred_new.append(1)\n# print(classification_report(y_test, y_pred_new, digits=4))\n\n# confusion_matrix(y_test, y_pred)\n\n# 3、经典-精确率、召回率、F1分数\n\nprint(\"训练精度: \", score2.mean())\nd = np.std(score2)\nprint(\"标准差: \", d)\nprecision_score(y_test, y_pred, average='micro')\nrecall_score(y_test, y_pred, average='micro')\nf1_score(y_test, y_pred, average='micro')\n\nprint(\"AUC:\", roc_auc)\n\n# 4、模型报告\nprint(classification_report(y_test, y_pred, digits=4))\n\nscore = lr_clf.score(std_Xtest, y_test)\nprint(\"测试精度: \", score)\n","repo_name":"dyeeee/760ProjectOWPrediction","sub_path":"FinalModel/Models_Final.py","file_name":"Models_Final.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"569219593","text":"# Author Grib ALI\n# From nes to ps3, all in one class\n# Not a good design decision\n# From ps4, every transition on it's own scene.\n\n# TODO\n# Complete titles + font & color text\n# Time ps3 to ps4\n\nfrom typing_extensions import runtime\nfrom manim import *\nimport os\n\nfrom manim.utils.rate_functions import ease_in_circ, ease_in_expo\n\nASSETS_PATH = os.getcwd() + \"/assets/\"\n\n\ndef easeInOutCubic(x):\n from math import pow\n if x < .5:\n return 4 * x * x * x\n else:\n return 1 - pow(-2 * x + 2, 3) / 2\n\ndef get_obj_by_id(obj: VMobject, index: str) -> VMobject:\n for i in obj.submobjects:\n if i.id == index:\n print(\"found\", i.id)\n return i\n return None\n\ndef get_objs_by_ids_rest(obj, ids):\n \"\"\"\n This function gets all objects by id in ids\n and the rest as a VGroup\n Returns tuple(objs_by_ids, VGroup rest)\n \"\"\"\n objs = VGroup()\n rest = VGroup()\n for i in obj.submobjects:\n if i.id not in ids:\n rest.add(i)\n\n for i in ids:\n for subm in obj.submobjects:\n if subm.id == i:\n print(\"found\", i)\n objs.add(subm)\n break\n\n return (objs, rest)\n\n\ndef get_objs_by_ids(obj, ids):\n \"\"\"\n This function gets all objects by id in ids\n and the rest as a VGroup\n Returns tuple(objs_by_ids, VGroup)\n \"\"\"\n objs = VGroup()\n for i in ids:\n for subm in obj.submobjects:\n if subm.id == i:\n print(\"found\", i)\n objs.add(subm)\n break\n\n return objs\n\ndef get_title(title: str) -> TextMobject:\n text_font = \"SF Pro Display\"\n text_color = WHITE\n text_coords = np.array([0, -3, 0])\n\n text = Text(\n title,\n font=text_font,\n color=text_color,\n weight=BOLD,\n )\n text.move_to(text_coords)\n return text\n\nclass ControllerEvolution(MovingCameraScene):\n\n def construct(self):\n self.text_font = \"SF Pro Display\"\n self.text_color = WHITE\n self.text_coords = np.array([0, -3, 0])\n\n # Background\n self.bg = ImageMobject(ASSETS_PATH + \"bg.jpg\")\n self.bg.z_index = -20\n self.add(self.bg)\n\n self.nes_snes()\n self.snes_ps1()\n self.ps1_n64()\n self.n64_ps2()\n self.ps2_xbox()\n self.xbox_gamecube()\n self.gamecube_wii()\n self.wii_xbox360()\n self.xbox360_ps3()\n\n # Helper function\n def get_title(self, title: str) -> TextMobject:\n text = Text(\n title,\n font=self.text_font,\n color=self.text_color,\n weight=BOLD,\n )\n text.move_to(self.text_coords)\n return text\n \n\n def nes_snes(self):\n self.nes = SVGMobject(ASSETS_PATH + \"nes.svg\")\n self.snes = SVGMobject(ASSETS_PATH + \"snes.svg\")\n a_button = get_objs_by_ids(self.nes, [\"a_button\", \"a\"])\n b_button = get_objs_by_ids(self.nes, [\"b_button\", \"b\"])\n dpad = get_objs_by_ids(self.nes, [\"dpad\", \"dpad_outter\", \"dpad_center\"])\n dpad_snes = get_obj_by_id(self.snes, \"dpad\")\n red = get_obj_by_id(self.snes, \"red\")\n green = get_obj_by_id(self.snes, \"green\")\n start = get_obj_by_id(self.nes, \"start\")\n select = get_obj_by_id(self.nes, \"select\")\n ss = VGroup(start, select)\n start_s = get_obj_by_id(self.snes, \"start_select\")\n temp, body_nes = get_objs_by_ids_rest(self.nes, [\"a_button\", \"a\", \"b\", \"b_button\",\n \"dpad\", \"dpad_outter\", \"dpad_center\",\n \"start\", \"select\"])\n temp, body_snes = get_objs_by_ids_rest(self.snes, [\n \"dpad\", \"green\", \"red\", \"start_select\"\n ])\n\n self.title_nes = self.get_title(\"NES\")\n self.title_snes = self.get_title(\"SNES\")\n \n self.play(\n LaggedStart(\n DrawBorderThenFill(self.nes),\n AddTextLetterByLetter(self.title_nes),\n )\n )\n for i in body_nes:\n i.z_index =- 1\n self.wait(.2)\n self.play(\n ReplacementTransform(\n body_nes,\n body_snes\n ),\n LaggedStart(\n ReplacementTransform(\n a_button,\n red\n ),\n ReplacementTransform(\n b_button,\n green\n ),\n ReplacementTransform(\n dpad,\n dpad_snes\n ),\n ReplacementTransform(\n start,\n start_s\n ),\n ReplacementTransform(\n ss,\n start_s\n ),\n FadeTransformPieces(\n self.title_nes,\n self.title_snes\n )\n ),\n rate_func=slow_into,\n\n )\n\n\n def snes_ps1(self):\n self.ps1 = SVGMobject(ASSETS_PATH + \"ps1\")\n self.title_ps1 = self.get_title(\"PlayStation 1\")\n snes_dpad = [\"dpad_circle\", \"dpad\"]\n snes_buttons = [\"red\", \"green\", \"blue\",\"yellow\"]\n self.ps1_dpad = [\"up\", \"right\", \"down\", \"left\"]\n self.ps1_buttons = [\"triangle\", \"circle\", \"cross\", \"square\"]\n snes_ss = [\"start_select\"]\n ps1_ss = [\"start\", \"select\"]\n snes_triggers = [\"triggers\"]\n self.ps1_triggers = [\"left_trigger\", \"right_trigger\"]\n\n snes_buttons_obj = get_objs_by_ids(self.snes, snes_buttons)\n snes_dpad_obj = get_objs_by_ids(self.snes, snes_dpad)\n self.ps1_dpad_obj = get_objs_by_ids(self.ps1, self.ps1_dpad)\n self.ps1_buttons_obj = get_objs_by_ids(self.ps1, self.ps1_buttons)\n snes_ss_obj = get_objs_by_ids(self.snes, snes_ss)\n snes_triggers_obj = get_objs_by_ids(self.snes, snes_triggers)\n self.ps1_ss_obj = get_objs_by_ids(self.ps1, ps1_ss)\n self.ps1_triggers_obj = get_objs_by_ids(self.ps1, self.ps1_triggers)\n\n temp, snes_body = get_objs_by_ids_rest(\n self.snes,\n snes_dpad+snes_buttons+snes_ss+snes_triggers\n )\n temp, self.ps1_body = get_objs_by_ids_rest(\n self.ps1,\n self.ps1_dpad + self.ps1_buttons + ps1_ss + self.ps1_triggers\n )\n for i in self.ps1_body: i.z_index=-1\n self.play(\n ShrinkToCenter(snes_body),\n LaggedStart(*[\n ReplacementTransform(i, j)\n for i,j in [(snes_buttons_obj, self.ps1_buttons_obj),\n (snes_dpad_obj, self.ps1_dpad_obj),\n (snes_ss_obj, self.ps1_ss_obj),\n (snes_triggers_obj, self.ps1_triggers_obj)\n ]\n ],\n rate_func=rush_into,\n ),\n FadeTransformPieces(self.title_snes, self.title_ps1),\n GrowFromCenter(self.ps1_body, rate_func=slow_into, run_time=.5),\n )\n\n def ps1_n64(self):\n self.n64 = SVGMobject(ASSETS_PATH + \"n64.svg\")\n self.title_n64 = self.get_title(\"Nintendo 64\")\n for i in self.n64:i.set_stroke(width=.5)\n self.n64_buttons = [f\"yellow_{i}\" for i in range(1, 5)]\n self.rgb = [\"red\", \"green\", \"blue\"]\n self.rgb = [i + \"_button\" for i in self.rgb]\n self.n64_dpad = get_obj_by_id(self.n64, \"dpad\")\n self.rgb_obj = get_objs_by_ids(self.n64, self.rgb)\n print(10 * \"*\", len(self.rgb_obj))\n self.red, self.green, self.blue = self.rgb_obj\n self.n64_buttons_obj = get_objs_by_ids(self.n64, self.n64_buttons)\n self.n64_triggers = get_objs_by_ids(self.n64, self.ps1_triggers)\n temp, self.n64_body = get_objs_by_ids_rest(\n self.n64,\n self.ps1_triggers + self.n64_buttons + [\"dpad\"] + self.rgb\n )\n\n for i in self.n64_body: i.z_index=-1\n self.play(\n ReplacementTransform(\n self.ps1_body, self.n64_body\n ),\n LaggedStart(\n *[\n ReplacementTransform(i, j)\n for i, j in zip(self.ps1_buttons_obj, self.n64_buttons_obj)\n ]\n ),\n ReplacementTransform(self.ps1_dpad_obj, self.n64_dpad),\n ReplacementTransform(self.ps1_triggers_obj, self.n64_triggers),\n FadeOut(self.ps1_ss_obj),\n FadeTransformPieces(self.title_ps1, self.title_n64),\n rate_func = rush_into,\n )\n self.play(\n LaggedStart(*[\n GrowFromCenter(i)\n for i in self.rgb_obj\n ],lag_ratio=.4),\n rate_func = rush_into,\n run_time=.7\n )\n\n def n64_ps2(self):\n self.ps2 = SVGMobject(ASSETS_PATH + \"ps2\").scale(.8)\n self.title_ps2 = self.get_title(\"PlayStation 2\")\n for i in self.ps2:i.set_stroke(width=.1)\n handles = [\"left_handle\", \"right_handle\"]\n ps2_handles = get_objs_by_ids(self.ps2, handles)\n n64_handles = get_objs_by_ids(self.n64, handles)\n self.ps2_buttons = self.ps1_buttons\n self.ps2_buttons_shapes = [i + \"_button\" for i in self.ps2_buttons]\n self.ps2_buttons_obj = get_objs_by_ids(self.ps2, self.ps2_buttons)\n self.ps2_buttons_shapes_obj = get_objs_by_ids(self.ps2, self.ps2_buttons_shapes)\n self.ps2_dpad_obj = get_objs_by_ids(self.ps2, self.ps1_dpad)\n self.ps2_ssa = [\"start\", \"select\", \"analog\"]\n self.ps2_ssa_obj = get_objs_by_ids(self.ps2, self.ps2_ssa)\n self.ps2_triggers_obj = get_objs_by_ids(self.ps2, self.ps1_triggers)\n for i in self.ps2_triggers_obj: i.z_index=-2\n for i in self.n64_triggers: i.z_index=-2\n\n rest, self.ps2_body = get_objs_by_ids_rest(\n self.ps2,\n handles+self.ps2_buttons+self.ps2_buttons_shapes+\n self.ps2_ssa+self.ps1_triggers+self.ps1_dpad\n )\n for i in self.ps2_body:\n if i.id != \"body\":\n i.z_index = -1\n else:\n i.z_index = -3\n\n temp, self.n64_body = get_objs_by_ids_rest(\n self.n64,\n self.ps1_triggers+self.n64_buttons+[\"dpad\"]+handles\n )\n\n for i in self.n64_body: i.z_index=-1\n for i in n64_handles: i.z_index = -2\n for i in ps2_handles: i.z_index = -2\n\n\n\n self.play(\n FadeTransformPieces(n64_handles, ps2_handles),\n FadeTransformPieces(self.title_n64, self.title_ps2),\n rate_func=ease_in_expo,\n run_time=.7\n )\n self.play(\n FadeTransformPieces(self.n64_body, self.ps2_body),\n rate_func=ease_in_circ\n )\n self.play(\n LaggedStart(*[\n ReplacementTransform(i, j)\n for i,j in [\n (self.n64_dpad, self.ps2_dpad_obj),\n (self.n64_buttons_obj, self.ps2_buttons_shapes_obj),\n (self.n64_triggers, self.ps2_triggers_obj)\n ]\n ])\n )\n for i in self.ps2_buttons_obj:\n i.save_state()\n i.scale(10)\n self.play(\n LaggedStart(\n LaggedStart(*[\n GrowFromCenter(i)\n for i in self.ps2_ssa_obj\n ]),\n LaggedStart(*[\n Succession(\n FadeIn(i, run_time=.2),\n Restore(i, run_time=.5)\n )\n for i in self.ps2_buttons_obj\n ], lag_ratio=.3),\n lag_ratio=1\n )\n )\n self.wait(.2)\n\n def ps2_xbox(self):\n self.xbox = SVGMobject(ASSETS_PATH + \"xbox_fat.svg\")\n self.title_xbox = self.get_title(\"Xbox\")\n for i in self.xbox: i.set_stroke(BLACK, width=.1)\n self.xbox_button = [\n \"green\", \"yellow\", \"blue\", \"red\"\n ]\n self.xbox_letters = list(\"abxy\")\n self.analogs = [\"left_analog\", \"right_analog\"]\n self.xbox_button_obj = get_objs_by_ids(self.xbox, self.xbox_button)\n self.xbox_letters_obj = get_objs_by_ids(self.xbox, self.xbox_letters)\n self.xbox_analogs = get_objs_by_ids(self.xbox, self.analogs)\n self.xbox_dpad = get_objs_by_ids(self.xbox, \"dpad\")\n self.ps2_analogs = get_objs_by_ids(self.ps2, self.analogs)\n\n rest, self.ps2_body = get_objs_by_ids_rest(\n self.ps2,\n self.ps2_buttons+self.ps2_buttons_shapes+\n self.analogs+self.ps1_dpad\n )\n for i in self.ps2_body:\n i.z_index = -1\n\n rest, self.xbox_body = get_objs_by_ids_rest(\n self.xbox,\n self.xbox_button+self.analogs+self.xbox_letters+self.ps1_dpad\n )\n for i in self.xbox_body:\n i.z_index = -1\n\n self.play(\n ApplyMethod(self.ps2_buttons_obj.shift, 2 * UP, rate_func=rush_from),\n LaggedStart(\n ReplacementTransform(self.ps2_body, self.xbox_body),\n FadeTransformPieces(self.title_ps2, self.title_xbox),\n LaggedStart(*[\n ReplacementTransform(i, j)\n for i,j in [\n (self.ps2_analogs, self.xbox_analogs),\n (self.ps2_dpad_obj, self.xbox_dpad),\n (self.ps2_buttons_shapes_obj, self.xbox_button_obj)\n ]\n ]),\n lag_ratio=.6\n ),\n rate_func=rush_into\n )\n self.play(\n ReplacementTransform(self.ps2_buttons_obj, self.xbox_letters_obj),\n rate_func=rush_into\n )\n\n self.wait(.2)\n\n def xbox_gamecube(self):\n self.gamecube = SVGMobject(ASSETS_PATH + \"gamecube.svg\")\n self.title_gc = self.get_title(\"GameCube\")\n self.handles = [\"left_handle\", \"right_handle\"]\n x_body, x_rest = get_objs_by_ids_rest(self.xbox, [\"body\", \"upper_body\"])\n g_body, g_rest = get_objs_by_ids_rest(self.gamecube,\n [\"body\"]+self.handles)\n self.g_triggers = get_objs_by_ids(self.gamecube, self.ps1_triggers)\n g_rest.remove(*self.g_triggers)\n for i in self.g_triggers: i.z_index == -2\n self.play(\n LaggedStart(*[\n ApplyMethod(i.shift, 5 * DOWN)\n for i in x_rest\n ], lag_ratio=.2),\n run_time=2.5\n )\n self.play(\n ApplyMethod(x_body.set_color, \"#565E9E\"),\n run_time=.8,\n rate_func=ease_in_circ\n )\n self.play(\n LaggedStart(\n FadeTransformPieces(x_body, g_body),\n FadeTransformPieces(self.title_xbox, self.title_gc),\n FadeInFrom(self.g_triggers, 5 * UP),\n lag_ratio=.2\n )\n )\n self.play(\n LaggedStart(*[\n GrowFromCenter(i)\n for i in g_rest\n ], lag_ratio=.15),\n run_time=2\n )\n\n self.wait(.3)\n\n def gamecube_wii(self):\n self.wii = SVGMobject(ASSETS_PATH + \"wii.svg\")\n self.title_wii = self.get_title(\"Wii\")\n g_handles = get_objs_by_ids(self.gamecube, self.handles)\n right_buttons = get_objs_by_ids(self.gamecube,\n [f\"{i}_button\" for i in \"abxy\"]+list(\"abxy\")+\n [\"analog_base\", \"analog\", \"c\"]\n )\n g_handles[1].add(right_buttons)\n left_buttons = get_objs_by_ids(self.gamecube,\n [\"dpad\", \"left_analog_base\", \"left_analog\"])\n g_handles[0].add(left_buttons)\n body = get_objs_by_ids(self.gamecube,\n self.ps1_triggers+[\"right_trigger_thing\", \"body\", \"middle_button\"])\n\n wii_body, buttons = get_objs_by_ids_rest(self.wii, [\"body\"])\n\n def updater_handles(obj, dt):\n h1, h2 = obj\n value = dt\n speed = 4\n rot_speed = 3\n h1.shift(value * speed * UL)\n h2.shift(value * speed * DR)\n h1.rotate(value * rot_speed * PI)\n h2.rotate(value * rot_speed * PI)\n\n g_handles = g_handles.clear_updaters()\n g_handles.add_updater(updater_handles)\n\n\n self.play(\n Rotate(body, 90 * DEGREES),\n g_handles.animate.update()\n )\n g_handles.clear_updaters()\n self.remove(g_handles)\n self.play(\n LaggedStart(\n FadeTransformPieces(body, wii_body),\n FadeTransformPieces(self.title_gc, self.title_wii),\n LaggedStart(*[\n GrowFromCenter(i)\n for i in buttons\n ])\n )\n )\n\n self.wait(.3)\n\n def wii_xbox360(self):\n self.xbox360 = SVGMobject(ASSETS_PATH + \"xbox360.svg\")\n self.title_xb360 = self.get_title(\"Xbox 360\")\n for i in self.xbox360.submobjects: i.set_stroke(color=BLACK, width=.1)\n self.play(\n FadeTransformPieces(self.wii, self.xbox360),\n FadeTransformPieces(self.title_wii, self.title_xb360),\n )\n self.wait(.3)\n\n def xbox360_ps3(self):\n self.ps3 = SVGMobject(ASSETS_PATH + \"ps3.svg\")\n self.title_ps3 = self.get_title(\"PlayStation 3\")\n for i in self.xbox360.submobjects: i.set_stroke(color=BLACK, width=.1)\n for i in self.ps3.submobjects: i.set_stroke(color=BLACK, width=.1)\n\n #directions for the animation\n directions = [UP, UP, UP+.2*RIGHT, RIGHT, DOWN, UL, UR, UL, DL]\n\n #objects to retreive from the xbox controller\n triggers = get_objs_by_ids(self.xbox360, self.ps1_triggers)\n buttons = [[f\"{i}_button\", i] for i in \"ybax\"]\n buttons_obj = []\n for i in buttons:\n button = get_objs_by_ids(self.xbox360, i)\n buttons_obj.append(button)\n start_back = [[f\"{i}_rect\", i] for i in [\"start\", \"back\"]]\n start_back_obj = []\n for i in start_back:\n s = get_objs_by_ids(self.xbox360, i)\n start_back_obj.append(s)\n\n dpad = [\"dpad\", \"dpad_inner\"]\n dpad_obj = get_objs_by_ids(self.xbox360, dpad)\n\n xbox_objs = [*triggers, *buttons_obj, *start_back_obj, dpad_obj]\n\n sb = [*start_back[0], *start_back[1]] #flattened version of start_back\n rest, xbox_body = get_objs_by_ids_rest(\n self.xbox360,\n self.ps1_triggers+buttons+sb+dpad\n )\n\n #ps3 objects\n buttons_ps3 = [[f\"{i}_button\", i] for i in [\"triangle\", \"circle\", \"cross\", \"square\"]]\n buttons_ps3_obj = []\n for i in buttons_ps3:\n button = get_objs_by_ids(self.ps3, i)\n buttons_ps3_obj.append(button)\n\n triggers_ps3 = get_objs_by_ids(self.ps3, self.ps1_triggers)\n ss_ps3 = [\"start\", \"select\"]\n ss_ps3_obj = [*get_objs_by_ids(self.ps3, ss_ps3)]\n dpad_ps3 = [\"up\", \"right\", \"down\", \"left\"]\n dpad_ps3_obj = get_objs_by_ids(self.ps3, dpad_ps3)\n\n ps3_objs = [*triggers_ps3, *buttons_ps3_obj, *ss_ps3_obj, dpad_ps3_obj]\n #flatten the buttons_ps3\n bps3 = []\n for i in buttons_ps3:\n bps3.append(i[0])\n bps3.append(i[1])\n\n rest, ps3_body = get_objs_by_ids_rest(\n self.ps3,\n self.ps1_triggers+bps3+ss_ps3+dpad_ps3\n )\n for i in triggers_ps3: i.z_index = -2\n for i in triggers: i.z_index = -2\n for i in ps3_body: i.z_index = 0\n\n\n\n\n\n\n def updater_handles(direction):\n def updater(obj, dt):\n value = dt\n speed = 4\n rot_speed = 3\n obj.shift(value * speed * direction)\n obj.rotate(value * rot_speed * PI)\n return updater\n\n for index, obj in enumerate(xbox_objs):\n obj.clear_updaters()\n obj.add_updater(updater_handles(directions[index]))\n\n self.play(\n *[\n i.animate.update()\n for i in xbox_objs\n ]\n )\n for i in xbox_objs: i.clear_updaters()\n self.play(\n FadeTransformPieces(xbox_body, ps3_body),\n FadeTransformPieces(self.title_xb360, self.title_ps3)\n )\n self.play(\n LaggedStart(*[\n Transform(i, j)\n for i,j in zip(xbox_objs, ps3_objs)\n ]),\n rate_func=rush_into\n )\n self.pss = ps3_objs\n\n self.wait(.3)\n\n\nclass ControllerPS3ToPS4(Scene):\n # TODO:\n # Add Triggers\n\n def construct(self):\n # Background\n self.bg = ImageMobject(ASSETS_PATH + \"bg.jpg\")\n self.bg.z_index = -20\n self.add(self.bg)\n\n self.ps3 = SVGMobject(ASSETS_PATH + \"ps3.svg\")\n for i in self.ps3.submobjects:\n i.set_stroke(width=.5)\n self.title_ps3 = get_title(\"PlayStation 3\")\n self.title_ps4 = get_title(\"PlayStation 4\")\n self.ps4 = SVGMobject(ASSETS_PATH + \"ps4_2.svg\")\n self.add(self.ps3)\n self.add(self.title_ps3)\n l = Line(\n UP,\n DOWN,\n color=WHITE,\n stroke_width=.8,\n )\n l.z_index = -9\n lines_coors = [\n (-2, 1), (-1.5, 3.5),\n (2.7, 1),(3, .5),\n (1,4), (-2, -1) \n ]\n arrays = [\n np.array([x, y, 0])\n for x, y in lines_coors\n ]\n lines = VGroup(*[\n l.copy().shift(i)\n for i in arrays\n ])\n for i in lines:\n i.z_index = -9\n\n\n \"\"\"getting the buttons\"\"\"\n buttons_ps3 = VGroup()\n shapes_ps3 = VGroup()\n buttons_ps4 = VGroup()\n shapes_ps4 = VGroup()\n for i in (\"cross\", \"triangle\", \"square\", \"circle\"):\n # button: the circle\n # shape: cross, triangle, etc...\n button_ps3 = get_obj_by_id(self.ps3, f\"{i}_button\")\n button_ps4 = get_obj_by_id(self.ps4, f\"{i}_button\")\n shape_ps3 = get_obj_by_id(self.ps3, i)\n shape_ps4 = get_obj_by_id(self.ps4, i)\n\n shape_ps3.z_index = 3\n shape_ps4.z_index = 3\n button_ps4.z_index = 2\n button_ps3.z_index = 2\n\n buttons_ps3.add(button_ps3)\n buttons_ps4.add(button_ps4)\n shapes_ps3.add(shape_ps3)\n shapes_ps4.add(shape_ps4)\n dpad_ps3 = get_objs_by_ids(self.ps3, [\"up\", \"down\", \"left\", \"right\"])\n analogs = [\"_analog_base\", \"_analog\", \"_analog_inner\"]\n left_analog = [\"left\"+i for i in analogs]\n right_analog = [\"right\"+i for i in analogs]\n\n\n analogs_ps3 = get_objs_by_ids(self.ps3,\n left_analog+right_analog)\n analogs_ps4 = get_objs_by_ids(self.ps4,\n left_analog+right_analog)\n # Bodies\n left_handle = get_obj_by_id(self.ps3, \"left_handle\")\n right_handle = get_obj_by_id(self.ps3, \"right_handle\")\n left_handle_4 = get_obj_by_id(self.ps4, \"left_handle\")\n right_handle_4 = get_obj_by_id(self.ps4, \"right_handle\")\n\n body_ps4 = get_obj_by_id(self.ps4, \"body_center\")\n body_ps3 = get_objs_by_ids(self.ps3, [\n \"body_center\",\n \"body_center_inner\",\n ])\n ss = get_objs_by_ids(self.ps3, [\n \"start\",\n \"select\"\n ])\n sm = get_objs_by_ids(self.ps4, [\n \"share\",\n \"menu\"\n ])\n\n ss_text = get_objs_by_ids(self.ps3, [\n \"start_txt\",\n \"select_txt\"\n ])\n\n dpad_ps4 = get_obj_by_id(self.ps4, \"arrows\")\n logo = [\"ps_logo_bg\", \"ps_logo\"]\n logo_ps3 = get_objs_by_ids(self.ps3, logo)\n logo_ps3.z_index = 4\n logo_ps4 = get_objs_by_ids(self.ps4, logo)\n lights = [f\"light_{i}\" for i in range(1, 5)]\n lights_ps3 = get_objs_by_ids(self.ps3, lights)\n trackpad = get_obj_by_id(self.ps4, \"trackpad\")\n \n triggers = [\"left_trigger\", \"right_trigger\"]\n self.triggers = get_objs_by_ids(self.ps4, triggers)\n for i in self.triggers:\n i.z_index = -2\n trackpad.z_index = 4\n mic = get_obj_by_id(self.ps4, \"mic\")\n mic.z_index = 4\n right_extreme = get_obj_by_id(self.ps4, \"right_extreme\")\n left_extreme = get_obj_by_id(self.ps4, \"left_extreme\")\n right_extreme.z_index = 4\n left_extreme.z_index = 4\n\n buttons_flight = AnimationGroup(\n LaggedStart(*[\n ShowPassingFlash(i, time_width=.3, rate_func=linear)\n for i in lines\n ],\n lag_ratio=.4\n ),\n # WiggleOutThenIn(img, rotation_angle=0.01*.5*TAU,scale_value=1, n_wiggles=20, rate_func=linear)\n buttons_ps3.animate.shift(1.5*UP),\n shapes_ps3.animate.shift(1.5*UP),\n dpad_ps3.animate.shift(1.5*UP),\n analogs_ps3.animate.shift(1.5*UP),\n ss.animate.shift(1.5*UP),\n logo_ps3.animate.shift(1.5*UP),\n rate_func=linear,\n run_time=1\n )\n\n\n text_lights_fading = AnimationGroup(\n LaggedStart(*[\n ShrinkToCenter(i)\n for i in [*lights_ps3, *ss_text]\n ]),\n rate_func=linear,\n )\n\n self.play(\n LaggedStart(\n buttons_flight,\n text_lights_fading,\n lag_ratio=.5\n )\n )\n\n transforms_body = AnimationGroup(\n FadeTransform(left_handle, left_handle_4),\n FadeTransform(right_handle, right_handle_4),\n FadeTransform(body_ps3, body_ps4),\n rate_func=linear,\n run_time=.7\n \n )\n transforms_buttons = AnimationGroup(\n LaggedStart(\n LaggedStart(*[\n Transform(i, j)\n for i, j in zip(buttons_ps3, buttons_ps4)\n ]),\n LaggedStart(*[\n Transform(i, j)\n for i, j in zip(shapes_ps3, shapes_ps4)\n ]),\n lag_ratio=1\n ),\n FadeTransformPieces(dpad_ps3, dpad_ps4),\n FadeTransform(ss[0], sm[1]),\n FadeTransform(ss[1], sm[0]),\n FadeTransform(analogs_ps3, analogs_ps4),\n logo_ps3.animate.move_to(logo_ps4)\n )\n self.play(\n LaggedStart(\n transforms_body,\n transforms_buttons,\n FadeTransformPieces(self.title_ps3, self.title_ps4),\n lag_ratio=.3\n )\n )\n for i in lines:\n i.rotate(180 * DEGREES)\n\n trackpad.shift(5*UP)\n # right and left coefficient\n rl_coeff = 1\n # down coefficient\n d_coeff = 4\n\n self.play(\n LaggedStart(\n GrowFromCenter(mic),\n FadeInFrom(right_extreme, rl_coeff * RIGHT + d_coeff * DOWN),\n FadeInFrom(left_extreme, rl_coeff * LEFT + d_coeff * DOWN),\n ),\n\n run_time=.4\n )\n self.play(\n FadeInFrom(self.triggers, 2 * UP),\n rate_func=ease_in_expo,\n run_time=.3\n )\n self.play(\n LaggedStart(*[\n ShowPassingFlash(i, time_width=.3, rate_func=linear)\n for i in lines\n ],\n lag_ratio=.3\n ),\n trackpad.animate.shift(5*DOWN),\n rate_func=linear,\n )\n self.wait(.1)\n\n\nclass ControllerPS4ToXboxOne(Scene):\n \"\"\"\n Transition PS4 -> Xbox One\n \"\"\"\n \n def construct(self):\n self.prepare()\n self.start_animation()\n\n def prepare(self):\n # Background\n self.bg = ImageMobject(ASSETS_PATH + \"bg.jpg\")\n self.bg.z_index = -20\n self.add(self.bg)\n\n self.ps4 = SVGMobject(ASSETS_PATH + \"ps4_2.svg\")\n self.xbox1 = SVGMobject(ASSETS_PATH + \"xbox_one.svg\")\n self.title_ps4 = get_title(\"PlayStation 4\")\n self.title_xbox1 = get_title(\"Xbox One\")\n\n self.ps4_body, self.ps4_rest = get_objs_by_ids_rest(\n self.ps4,[\n \"body_center\",\n \"left_handle\",\n \"right_handle\",\n \"right_trigger\",\n \"left_trigger\",\n \"trackpad\",\n \"left_analog_base\",\n \"right_analog_base\"\n ]\n )\n\n self.ps4_color = \"#222629\"\n\n # Xbox One defs\n self.xbox1_body = get_obj_by_id(self.xbox1, \"body\")\n self.xbox1_upper = get_obj_by_id(self.xbox1, \"upper_side\")\n self.xbox1_logo = get_obj_by_id(self.xbox1, \"logo\")\n self.xbox1_triggers = get_obj_by_id(self.xbox1, \"triggers\")\n self.xbox1_buttons = VGroup()\n self.xbox1_letters = VGroup()\n for i in list(\"xyba\"):\n button = get_obj_by_id(self.xbox1, f\"{i}_button\")\n letter = get_obj_by_id(self.xbox1, i)\n self.xbox1_buttons.add(button)\n self.xbox1_letters.add(letter)\n\n self.xbox1_view = get_objs_by_ids(self.xbox1, [\"view\", \"view_icon\"])\n self.xbox1_menu = get_objs_by_ids(self.xbox1, [\"menu\", \"menu_icon\"])\n self.xbox1_dpad = get_objs_by_ids(self.xbox1, [\"dpad\", \"dpad_holder\"])\n analog = [\"analog_base\", \"analog_outter\", \"analog\", \"analog_inner\"]\n left_analogs = [\"left_\"+i for i in analog]\n right_analogs = [\"right_\"+i for i in analog]\n self.xbox1_left_analog = get_objs_by_ids(self.xbox1, left_analogs)\n self.xbox1_right_analog = get_objs_by_ids(self.xbox1, right_analogs)\n\n def start_animation(self):\n self.add(self.ps4, self.title_ps4)\n self.play(\n self.ps4.animate.set_color(self.ps4_color),\n run_time=.5\n )\n self.remove(*self.ps4_rest)\n self.wait(.1)\n self.play(\n ClockwiseTransform(self.ps4_body, self.xbox1_body),\n FadeTransformPieces(self.title_ps4, self.title_xbox1),\n rate_func=ease_in_circ,\n run_time=.7\n )\n self.play(\n LaggedStart(\n DrawBorderThenFill(self.xbox1_upper), #run_time=.8),\n FadeInFrom(self.xbox1_triggers, UP),\n GrowFromCenter(self.xbox1_logo),\n lag_ratio=.25\n )\n )\n self.play(\n LaggedStart(\n LaggedStart(*[\n GrowFromCenter(i)\n for i in self.xbox1_buttons\n ]),\n LaggedStart(*[\n DrawBorderThenFill(i, run_time=.7)\n for i in self.xbox1_letters\n ]),\n LaggedStart(\n GrowFromCenter(self.xbox1_menu[0]),\n FadeIn(self.xbox1_menu[1]),\n GrowFromCenter(self.xbox1_view[0]),\n FadeIn(self.xbox1_view[1]),\n lag_ratio=.2\n ),\n LaggedStart(\n LaggedStart(*[\n GrowFromCenter(i)\n for i in self.xbox1_right_analog\n ]),\n LaggedStart(*[\n GrowFromCenter(i)\n for i in self.xbox1_left_analog\n ]),\n LaggedStart(\n GrowFromCenter(self.xbox1_dpad[1]),\n DrawBorderThenFill(self.xbox1_dpad[0], run_time=.6),\n ),\n lag_ratio=.4\n ), \n lag_ratio=.4\n )\n )\n self.wait(.1)\n\n\nclass ControllerXboxOneSwitch(MovingCameraScene):\n\n def construct(self):\n self.prepare()\n self.start_animations()\n self.switch_pro()\n self.ps5_meme()\n\n def prepare(self):\n self.bg = ImageMobject(ASSETS_PATH + \"bg.jpg\")\n self.bg.z_index = -20\n self.add(self.bg)\n self.title_xbox1 = get_title(\"Xbox One\")\n self.title_switch = get_title(\"Switch\")\n\n self.xbox1 = SVGMobject(ASSETS_PATH + \"xbox_one.svg\")\n self.switch = SVGMobject(ASSETS_PATH + \"switch.svg\")\n self.pro_con = SVGMobject(ASSETS_PATH + \"switch_pro.svg\").set_y(-1)\n self.ps5 = SVGMobject(ASSETS_PATH + \"ps5.svg\")\n self.stockless = ImageMobject(ASSETS_PATH + \"stockless.png\")\n\n cons = [\"right_con\", \"left_con\"]\n self.right_con = get_obj_by_id(self.switch, cons[0])\n self.left_con = get_obj_by_id(self.switch, cons[1])\n body = [\"screen_border\", \"bezels\", \"screen\"]\n self.body = get_objs_by_ids(self.switch, body)\n\n left_x = self.left_con.get_edge_center(RIGHT)[0] * RIGHT\n right_x = self.right_con.get_edge_center(LEFT)[0] * RIGHT\n triggers = [\"left_trigger\", \"right_trigger\"]\n self.triggers = get_objs_by_ids(self.switch, triggers)\n for i in self.triggers:\n i.z_index = -1\n\n temp, self.buttons = get_objs_by_ids_rest(\n self.switch,\n body+triggers+cons\n )\n\n\n self.left_rect = Polygon(\n left_x + 4 * UP,\n left_x + 4 * DOWN,\n (left_x + 4 * DOWN) + 6 * LEFT,\n (left_x + 4 * UP) + 6 * LEFT,\n fill_color=\"#01bbe2\",\n fill_opacity=1,\n stroke_width=0\n )\n\n self.right_rect = Polygon(\n right_x + 4 * UP,\n right_x + 4 * DOWN,\n (right_x + 4 * DOWN) - 6 * LEFT,\n (right_x + 4 * UP) - 6 * LEFT,\n fill_color=\"#fe5d53\",\n fill_opacity=1,\n stroke_width=0\n )\n\n self.center_rect = Polygon(\n right_x + 4 * UP,\n right_x + 4 * DOWN,\n left_x + 4 * DOWN,\n left_x + 4 * UP,\n fill_color=\"#606062\",\n fill_opacity=1,\n stroke_width=0\n )\n\n\n\n def start_animations(self):\n self.add(self.xbox1, self.title_xbox1)\n self.play(\n FadeInFrom(self.left_rect, 7 * UP),\n FadeInFrom(self.right_rect, 7 * DOWN),\n FadeIn(self.center_rect)\n )\n self.remove(self.xbox1, self.title_xbox1)\n self.wait(.1)\n self.play(\n ReplacementTransform(self.left_rect, self.left_con),\n ReplacementTransform(self.right_rect, self.right_con),\n FadeTransform(self.center_rect, self.body),\n FadeInFrom(self.title_switch, DOWN)\n )\n self.play(\n LaggedStart(*[\n GrowFromCenter(i)\n for i in self.buttons\n ],\n lag_ratio=.1\n ),\n run_time=2\n )\n self.play(\n FadeInFrom(self.triggers, 3 * UP, rate_func=ease_in_circ),\n run_time=.6\n )\n\n def switch_pro(self):\n self.left_con.z_index = 5\n self.right_con.z_index = 5\n self.left_con.add(self.triggers[0])\n self.right_con.add(self.triggers[1])\n\n for i in self.buttons:\n i.z_index = 5\n if i.get_x() < 0:\n self.left_con.add(i)\n else:\n self.right_con.add(i)\n self.play(\n self.left_con.animate.shift(2 * UP),\n self.right_con.animate.shift(2 * UP),\n FadeTransformPieces(self.body, self.pro_con),\n run_time=.6\n )\n right_translation = 1.293 * LEFT\n left_translation = 1.25 * RIGHT\n self.play(\n self.left_con.animate.shift(left_translation),\n self.right_con.animate.shift(right_translation),\n rate_func=ease_in_circ,\n run_time=.6\n )\n\n self.play(\n self.pro_con.animate.shift(UP),\n LaggedStart(\n self.right_con.animate.shift(2 * DOWN),\n self.left_con.animate.shift(2 * DOWN),\n lag_ratio=.3\n ),\n rate_func=smooth,\n run_time=.6\n )\n self.wait(.1)\n\n def ps5_meme(self):\n self.pro_con.add(*self.left_con)\n self.pro_con.add(*self.right_con)\n self.title_ps5 = get_title(\"PlayStation 5\")\n self.play(\n FadeTransformPieces(self.pro_con, self.ps5),\n FadeTransformPieces(self.title_switch, self.title_ps5),\n )\n self.play(\n FadeIn(self.stockless),\n run_time=.5\n )\n target = 1.5 * UP + .5 * RIGHT\n self.play(\n self.camera.frame.animate.scale(.3).move_to(target),\n run_time=.4\n )\n self.wait(.2)","repo_name":"AliNear/controllers","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":36888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30389211897","text":"\r\nimport numpy\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom keras.applications.resnet import ResNet50\r\nfrom tensorflow.python.keras.regularizers import L2\r\nfrom imblearn.over_sampling import SMOTE\r\nfrom matplotlib import pyplot\r\nfrom PIL import Image\r\n\r\n\r\nclass Classifier:\r\n def __init__(self, pixels, class_label, dataset):\r\n self.pixels = pixels\r\n self.class_label = class_label\r\n self.dataset = dataset\r\n\r\n def data_preprocessing(self): \r\n dataset_numpy = numpy.array(self.dataset)\r\n numpy.random.shuffle(dataset_numpy)\r\n shuffled_images = dataset_numpy[:,:-1]\r\n shuffled_labels = dataset_numpy[:,-1:] \r\n reshaped_images = numpy.reshape(shuffled_images, (len(shuffled_images), self.pixels, self.pixels, 3))\r\n reshaped_images = reshaped_images.astype('float32') \r\n train_images = reshaped_images[:-7000]\r\n train_labels = shuffled_labels[:-7000] \r\n test_images = reshaped_images[len(reshaped_images)-6000:]\r\n test_labels = shuffled_labels[len(shuffled_labels)-6000:] \r\n prediction_images = reshaped_images[len(reshaped_images)-1000:]\r\n prediction_labels = shuffled_labels[len(shuffled_labels)-1000:] \r\n return train_images, train_labels, test_images, test_labels, prediction_images, prediction_labels\r\n\r\n def construct_model(self):\r\n model = keras.Sequential([\r\n keras.layers.experimental.preprocessing.RandomFlip(\"horizontal_and_vertical\"),\r\n keras.layers.experimental.preprocessing.RandomRotation(0.8),\r\n ])\r\n wrapper_model = ResNet50(include_top=False, input_shape=(self.pixels, self.pixels, 3), pooling='avg',\r\n classes=30, weights='imagenet')\r\n for layer in wrapper_model.layers[:-250]:\r\n layer.trainable=False\r\n\r\n model.add(wrapper_model)\r\n model.add(keras.layers.Flatten())\r\n model.add(keras.layers.Dense(64, activation='relu'))\r\n model.add(keras.layers.Dense(30, activation='softmax'))\r\n return model\r\n\r\n\r\n def new_model(self):\r\n model = keras.Sequential([\r\n keras.layers.AveragePooling2D(6, 3, input_shape=(self.pixels, self.pixels, 1)),\r\n keras.layers.Conv2D(64, 3, activation='relu'),\r\n keras.layers.Conv2D(64, 3, activation='relu'),\r\n keras.layers.Conv2D(32, 3, activation='relu'),\r\n keras.layers.Flatten(),\r\n keras.layers.Dense(128, activation='relu'),\r\n keras.layers.Dense(30, activation='softmax')\r\n ])\r\n return model","repo_name":"cobellini/VisClassify","sub_path":"Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22274224342","text":"matrix = [\n [1,2,3],\n [4,5,6],\n [7,8,9]\n ]\n\ndef swap_values_in_matrix(x1, y1, x2, y2, matrix):\n temp_value = matrix[y1][x1]\n matrix[y1][x1] = matrix[y2][x2]\n matrix[y2][x2] = temp_value\n\ndef rotate_matrix(matrix):\n for y in range(0, len(matrix)):\n for x in range(y, len(matrix[y])):\n swap_values_in_matrix(x1=x, y1=y, x2=y, y2=x, matrix=matrix)\n \n for y in range(0, len(matrix)):\n x_swap = len(matrix[y]) - 1\n for x in range(0, int(x_swap / 2)):\n swap_values_in_matrix(x1=x, y1=y, x2=x_swap, y2=y, matrix=matrix)\n x_swap -= 1\n\nrotate_matrix(matrix)\nprint(matrix)","repo_name":"jeremymec/algos","sub_path":"arrays_and_strings/1.7_rotate_matrix/rotate_matrix.py","file_name":"rotate_matrix.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"25374209928","text":"#print(\"I am AUTOBOT v1.0\")\n#print(\"o----\")\n#print(\" ||||\")\n#print (\"*\" * 10)\n\n'''price = 10\nrating = 4.8\nname = 'Roy'\nis_published = True\nprint(price)'''\n\n'''full_name = 'John Smith'\nage = 20\nis_new = True'''\n\n#name = input('What is your name? ')\n#print('Hi ' + name)\n#favorite_color = input(\"What's your favorite color? \" )\n#print(name + \" likes \" + favorite_color)\n\nrun = str(25)\nrun1 = run[-1]\nprint(run1)","repo_name":"codebreaker0909/Thor","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26606219338","text":"import argparse\nimport random\nfrom environment import TreasureCube\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nclass QLearningAgent(object):\n def __init__(self, environment, epsilon=0.01, alpha=0.5, gamma=0.99):\n self.environment = environment\n self.action_space = ['left','right','forward','backward','up','down'] # in TreasureCube\n\n # INITIALISING THE Q_TABLE\n \n self.q_table = dict() # Store all Q-values in dictionary of dictionaries\n \n for x in range(4): # Loop through all possible grid spaces, create sub-dictionary for each\n for y in range(4):\n for z in range(4):\n self.q_table[(x,y,z)] = {'left':0,'right':0,'forward':0,'backward':0,'up':0,'down':0}\n #Initialise with zero values for possible moves\n \n #Initialize all parameters\n self.epsilon = epsilon\n self.alpha = alpha\n self.gamma = gamma\n \n def take_action(self, state):\n # Returns either the optimal action which will maximise the reward,\n # or a random exploratory action.\n # The above choice depends on the value of epsilon\n\n if np.random.uniform(0,1) < self.epsilon:\n action = self.action_space[np.random.randint(0, len(self.action_space))]\n \n else:\n qValues = self.q_table[self.environment.curr_pos]\n maxValue = max(qValues.values())\n action = np.random.choice([k for k, v in qValues.items() if v == maxValue])\n\n return action\n\n def train(self, state, action, next_state, reward):\n #Updates the Q-value table using Q-learning\n \n qValues = self.q_table[next_state]\n max_q_value = max(qValues.values())\n current_q_value = self.q_table[state][action]\n \n self.q_table[state][action] = current_q_value + self.alpha * (reward + self.gamma * max_q_value - current_q_value)\n\ndef test_cube(max_episode, max_step, q_plot, q_table_output, rendEnv_output, epiSummary):\n env = TreasureCube(max_step=max_step)\n agent = QLearningAgent(env)\n reward_per_episode = []\n totalSteps=0\n totalRewards=0\n \n for epsisode_num in range(0, max_episode):\n state = env.reset()\n terminate = False\n t=0\n episode_reward = 0\n while not terminate:\n state = env.curr_pos\n action = agent.take_action(state)\n reward, terminate, next_state = env.step(action)\n next_state = env.curr_pos\n\n if (rendEnv_output==True):\n env.render() \n print(f'step: {t}, action: {action}, reward: {reward}')\n t += 1\n \n #Updating the Q values\n agent.train(state, action, next_state, reward)\n state = next_state\n episode_reward += reward\n \n reward_per_episode.append(episode_reward)\n if epiSummary==True:\n print(f'epsisode: {epsisode_num}, total_steps: {t} episode reward: {episode_reward}')\n\n totalSteps+=t\n \n for r in range(len(reward_per_episode)):\n totalRewards += reward_per_episode[r]\n \n print(\"Average steps per episode=\", totalSteps/(max_episode))\n print(\"Average rewards per episode=\", totalRewards/(max_episode))\n\n if (q_table_output==True):\n qTableOutput(agent.q_table)\n\n if (q_plot==True):\n plt.plot(reward_per_episode)\n plt.ylabel('Reward per episode')\n plt.xlabel('Episode')\n plt.show()\n\nimport csv\ndef qTableOutput(d):\n df = pd.DataFrame(d.items(), columns=[\"state\", \"action\"])\n action = df[\"action\"].apply(pd.Series)\n\n frames = [df, action]\n results = pd.concat(frames, axis=1)\n results = results.drop(results.columns[1], axis=1)\n\n with pd.option_context('display.max_rows', None, 'display.max_columns', None):\n print(results)\n\n # Uncomment the following line if you want to save a csv\n #pd.DataFrame(results).to_csv(\"qTable.csv\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Test')\n parser.add_argument('--max_episode', type=int, default=500, help = 'Specify the maximum episodes eg. --max_episode 10')\n parser.add_argument('--max_step', type=int, default=500, help = 'Specify the maximum steps eg. --max_step 10')\n parser.add_argument('--q_plot', type=bool, default=False, help = 'Specify True if you want to see the trainning plot eg. --q_table_output True')\n parser.add_argument('--q_table_output', type=bool, default=False, help = 'Specify True if you want to see the final q table eg. --q_plot True')\n parser.add_argument('--rendEnv_output', type=bool, default=False, help = 'Specify True if you want to see the rendered environment output eg. --rendEnv_output True')\n parser.add_argument('--epiSummary', type=bool, default=False, help = 'Specify True if you want to see statistics summary for each episode eg. --epiSummary True')\n \n args = parser.parse_args()\n\n test_cube(args.max_episode, args.max_step, args.q_plot, args.q_table_output, args.rendEnv_output, args.epiSummary)\n","repo_name":"BisakhaD/NTU-CZ3005-Artificial-Intelligence","sub_path":"Assignment2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"13971870206","text":"\"\"\"\nInference code for DALL-E Mini, adapted from:\nhttps://github.com/borisdayma/dalle-mini/blob/main/tools/inference/inference_pipeline.ipynb\n\"\"\"\nimport io\nimport random\nimport typing\nfrom functools import partial\n\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nfrom dalle_mini import DalleBart, DalleBartProcessor\nfrom flax.jax_utils import replicate\nfrom flax.training.common_utils import shard_prng_key\nfrom loguru import logger\nfrom PIL import Image\nfrom vqgan_jax.modeling_flax_vqgan import VQModel\n\n# create a random key\nSEED = random.randint(0, 2**32 - 1)\nKEY = jax.random.PRNGKey(SEED)\n\n# DALLE_MODEL = \"dalle-mini/dalle-mini/mini-1:v0\"\nDALLE_MODEL = \"dalle-mini/dalle-mini/mega-1-fp16:latest\"\nDALLE_COMMIT_ID = None\n\nVQGAN_REPO = \"dalle-mini/vqgan_imagenet_f16_16384\"\nVQGAN_COMMIT_ID = \"e93a26e7707683d349bf5d5c41c5b0ef69b677a9\"\n\n# Generation params\nTOP_K = None\nTOP_P = None\nTEMPERATURE = None\nCONDITION_SCALE = 10.0\n\n\ndef init_models():\n \"\"\"\n Initialize the needed models and parameters for image from text generation.\n \"\"\"\n\n dalle_model, dalle_params = DalleBart.from_pretrained(\n DALLE_MODEL, revision=DALLE_COMMIT_ID, dtype=jnp.float16, _do_init=False\n )\n\n dalle_processor = DalleBartProcessor.from_pretrained(\n DALLE_MODEL, revision=DALLE_COMMIT_ID\n )\n\n vqgan, vqgan_params = VQModel.from_pretrained( # type: ignore\n VQGAN_REPO, revision=VQGAN_COMMIT_ID, _do_init=False\n )\n\n # replicate model params on device for faster inference\n dalle_params = replicate(dalle_params)\n vqgan_params = replicate(vqgan_params)\n\n return dalle_model, dalle_params, vqgan, vqgan_params, dalle_processor\n\n\n# Generate encoded image\n@partial(jax.pmap, axis_name=\"batch\", static_broadcasted_argnums=(3, 4, 5, 6, 7))\ndef _p_generate(\n tokenized_prompt,\n key,\n dalle_params,\n dalle_model,\n top_k,\n top_p,\n temperature,\n condition_scale,\n):\n return dalle_model.generate(\n **tokenized_prompt,\n prng_key=key,\n params=dalle_params,\n top_k=top_k,\n top_p=top_p,\n temperature=temperature,\n condition_scale=condition_scale,\n )\n\n\n# Decode image\n@partial(jax.pmap, axis_name=\"batch\", static_broadcasted_argnums=(2,))\ndef _p_decode(indices, vqgan_params, vqgan):\n return vqgan.decode_code(indices, params=vqgan_params)\n\n\ndef generate_images(\n *,\n prompt: str,\n dalle_model,\n dalle_params,\n vqgan,\n vqgan_params,\n dalle_processor,\n n_images_per_prompt: int,\n) -> typing.Iterable[io.BytesIO]:\n \"\"\"\n Generate a set of images from a prompt, write each to a BytesIO buffer,\n and yield each one.\n \"\"\"\n logger.info(f\"Generating {n_images_per_prompt} images for prompt: {prompt}\")\n # Tokenize the prompt\n tokenized_prompts = dalle_processor([prompt])\n tokenized_prompts = replicate(tokenized_prompts)\n\n # Get a new key\n for i in range(n_images_per_prompt):\n logger.info(f\"Generating image {i}\")\n global KEY\n KEY, sub_key = jax.random.split(KEY)\n\n # Generate images\n encoded_images = _p_generate(\n tokenized_prompts,\n shard_prng_key(sub_key),\n dalle_params,\n dalle_model,\n TOP_K,\n TOP_P,\n TEMPERATURE,\n CONDITION_SCALE,\n )\n\n # Remove BOS\n encoded_images = encoded_images.sequences[..., 1:]\n\n # Decode images\n decoded_images = _p_decode(encoded_images, vqgan_params, vqgan)\n decoded_images = decoded_images.clip(0.0, 1.0).reshape((-1, 256, 256, 3))\n for decoded_img in decoded_images:\n img = Image.fromarray(np.asarray(decoded_img * 255, dtype=np.uint8))\n img_buf = io.BytesIO()\n img.save(img_buf, format=\"png\")\n # Rewind to the beginning of the buf for readers\n img_buf.seek(0)\n yield img_buf\n","repo_name":"jasonnance/deathsaurus","sub_path":"deathsaurus/generate_image.py","file_name":"generate_image.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26740810802","text":"\"\"\"\nGaussian Process Example\n------------------------\nFigure 8.10\n\nAn example of Gaussian process regression. The upper-left panel shows three\nfunctions drawn from an unconstrained Gaussian process with squared-exponential\ncovari- ance of bandwidth h = 1.0. The upper-right panel adds two constraints,\nand shows the 2-sigma contours of the constrained function space. The\nlower-left panel shows the function space constrained by the points with error\nbars. The lower-right panel shows the function space constrained by 20 noisy\npoints drawn from f(x) = cos(x).\n\"\"\"\n# Author: Jake VanderPlas\n# License: BSD\n# The figure produced by this code is published in the textbook\n# \"Statistics, Data Mining, and Machine Learning in Astronomy\" (2013)\n# For more information, see http://astroML.github.com\n# To report a bug or issue, use the following forum:\n# https://groups.google.com/forum/#!forum/astroml-general\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.gaussian_process import GaussianProcess\n\n#----------------------------------------------------------------------\n# This function adjusts matplotlib settings for a uniform feel in the textbook.\n# Note that with usetex=True, fonts are rendered with LaTeX. This may\n# result in an error if LaTeX is not installed on your system. In that case,\n# you can set usetex to False.\nfrom astroML.plotting import setup_text_plots\nsetup_text_plots(fontsize=8, usetex=False)\n\n\n#------------------------------------------------------------\n# define a squared exponential covariance function\ndef squared_exponential(x1, x2, h):\n return np.exp(-0.5 * (x1 - x2) ** 2 / h ** 2)\n\n#------------------------------------------------------------\n# draw samples from the unconstrained covariance\nnp.random.seed(1)\nx = np.linspace(0, 10, 100)\nh = 1.0\n\nmu = np.zeros(len(x))\nC = squared_exponential(x, x[:, None], h)\ndraws = np.random.multivariate_normal(mu, C, 3)\n\n#------------------------------------------------------------\n# Constrain the mean and covariance with two points\nx1 = np.array([2.5, 7])\ny1 = np.cos(x1)\ngp1 = GaussianProcess(corr='squared_exponential', theta0=0.5,\n random_state=0)\ngp1.fit(x1[:, None], y1)\nf1, MSE1 = gp1.predict(x[:, None], eval_MSE=True)\nf1_err = np.sqrt(MSE1)\n\n#------------------------------------------------------------\n# Constrain the mean and covariance with two noisy points\n# scikit-learn gaussian process uses nomenclature from the geophysics\n# community, where a \"nugget\" can be specified. The diagonal of the\n# assumed covariance matrix is multiplied by the nugget. This is\n# how the error on inputs is incorporated into the calculation\ndy2 = 0.2\ngp2 = GaussianProcess(corr='squared_exponential', theta0=0.5,\n nugget=(dy2 / y1) ** 2, random_state=0)\ngp2.fit(x1[:, None], y1)\nf2, MSE2 = gp2.predict(x[:, None], eval_MSE=True)\nf2_err = np.sqrt(MSE2)\n\n\n#------------------------------------------------------------\n# Constrain the mean and covariance with many noisy points\nx3 = np.linspace(0, 10, 20)\ny3 = np.cos(x3)\ndy3 = 0.2\ny3 = np.random.normal(y3, dy3)\ngp3 = GaussianProcess(corr='squared_exponential', theta0=0.5,\n thetaL=0.01, thetaU=10.0,\n nugget=(dy3 / y3) ** 2,\n random_state=0)\ngp3.fit(x3[:, None], y3)\nf3, MSE3 = gp3.predict(x[:, None], eval_MSE=True)\nf3_err = np.sqrt(MSE3)\n\n# we have fit for the `h` parameter: print the result here:\n\n\n\n#------------------------------------------------------------\n# Plot the diagrams\nfig = plt.figure(figsize=(5, 5))\n\n\n# first: plot a selection of unconstrained functions\nax = fig.add_subplot(221)\nax.plot(x, draws.T, '-k')\nax.set_ylabel('$f(x)$')\n\n# second: plot a constrained function\nax = fig.add_subplot(222)\nax.plot(x, f1, '-', color='gray')\nax.fill_between(x, f1 - 2 * f1_err, f1 + 2 * f1_err, color='gray', alpha=0.3)\nax.plot(x1, y1, '.k', ms=6)\n\n\n# third: plot a constrained function with errors\nax = fig.add_subplot(223)\nax.plot(x, f2, '-', color='gray')\nax.fill_between(x, f2 - 2 * f2_err, f2 + 2 * f2_err, color='gray', alpha=0.3)\nax.errorbar(x1, y1, dy2, fmt='.k', ms=6)\n\nax.set_xlabel('$x$')\nax.set_ylabel('$f(x)$')\n\n# third: plot a more constrained function with errors\nax = fig.add_subplot(224)\nax.plot(x, f3, '-', color='gray')\nax.fill_between(x, f3 - 2 * f3_err, f3 + 2 * f3_err, color='gray', alpha=0.3)\nax.errorbar(x3, y3, dy3, fmt='.k', ms=6)\n\nax.plot(x, np.cos(x), ':k')\n\nax.set_xlabel('$x$')\n\nfor ax in fig.axes:\n ax.set_xlim(0, 10)\n\nplt.show()\n","repo_name":"fenghaotong/AstroML","sub_path":"chapter8/fig_gp_example.py","file_name":"fig_gp_example.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"85"} +{"seq_id":"23421713855","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 22 14:27:52 2019\r\n\r\n@author: 拔凉拔凉冰冰凉\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nresult = []\r\nfilename = \"./test_A_s_result.txt\"\r\nwith open(filename, \"r\", encoding=\"utf-8\") as f:\r\n lines = f.readlines()\r\n# print(len(lines))\r\n for line in lines:\r\n line = line.split(\"\\n\")[0]\r\n line = line[:-1]\r\n# print(line)\r\n line = line.split(\" \")\r\n r = []\r\n for s in line:\r\n# print(s)\r\n r.append(float(s))\r\n result.append(r)\r\n f.close()\r\n \r\nal_name = ['centralized(c=4)', \"greedyCover\", \"greedyUtility\", \"centralized(c=1)\"]\r\ncolor = [\"r\", \"b\", \"g\", \"orange\"]\r\n\r\nprint(result)\r\n\r\nx = np.arange(30, 390, 30)\r\n\r\nplt.figure(figsize=(20, 17))\r\nplt.xticks(x)\r\nplt.ylim((0.3, 0.8))\r\nfor i in range(len(result)):\r\n plt.plot(x, result[i], c=color[i])\r\nplt.show()","repo_name":"menglei5633/charger","sub_path":"show_result.py","file_name":"show_result.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71274108757","text":"import re\n\nfrom ..model import FriendMsg, GroupMsg\nfrom ..refine import refine_pic_friend_msg, refine_pic_group_msg\n\n\ndef in_content(string: str, raw: bool = True):\n \"\"\"Content字段包括指定字符串 GroupMsg, FriendMsg\n\n :param string: 需要包含的字符串, 支持使用正则查找\n :param raw: 为True则使用最原始的Content字段数据进行查找, 即图片这类消息会包含图片链接、\n 图片MD5之类的数据; 为False则会提取真正发送的文字部分内容\n \"\"\"\n\n def deco(func):\n def inner(ctx):\n assert isinstance(ctx, (GroupMsg, FriendMsg))\n if raw:\n if re.match(string, ctx.Content):\n return func(ctx)\n else:\n if isinstance(ctx, GroupMsg):\n pic_ctx = refine_pic_group_msg(ctx)\n else:\n pic_ctx = refine_pic_friend_msg(ctx)\n if pic_ctx is not None:\n content = pic_ctx.Content\n else:\n content = ctx.Content\n if re.match(string, content):\n return func(ctx)\n return None\n\n return inner\n\n return deco\n","repo_name":"CrazyGriferman/PiaoQQBot","sub_path":"botoy/decorators/_in_content.py","file_name":"_in_content.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34115889652","text":"\"\"\"\n Given an array nums and a value val, remove all instances of that value \n in-place and return the new length.\n Do not allocate extra space for another array, you must do this by modifying \n the input array in-place with O(1) extra memory.\n The order of elements can be changed. It doesn't matter what you leave \n beyond the new length.\n \n Example:\n Given nums = [3,2,2,3], val = 3,\n Your function should return length = 2, with the first two elements of nums \n being 2.\n It doesn't matter what you leave beyond the returned length.\n\"\"\"\n#Difficulty: Easy\n#113 / 113 test cases passed.\n#Runtime: 28 ms\n#Memory Usage: 13.6 MB\n\n#Runtime: 28 ms, faster than 88.43% of Python3 online submissions for Remove Element.\n#Memory Usage: 13.6 MB, less than 6.06% of Python3 online submissions for Remove Element.\n\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n length = len(nums)-1\n while val in nums:\n if nums[length] == val:\n nums.pop(length)\n length-=1 \n return len(nums)\n","repo_name":"YuriSpiridonov/LeetCode","sub_path":"Easy/27.RemoveElement.py","file_name":"27.RemoveElement.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"85"} +{"seq_id":"71804248918","text":"import argparse\n\nimport h5py\nimport numpy as np\nimport scipy\nimport scipy.io as io\nfrom scipy.ndimage.filters import gaussian_filter\nfrom scipy.spatial import KDTree\nimport os\nfrom matplotlib import pyplot as plt\nfrom pathlib import Path\nimport threading\nimport multiprocessing\nimport json\nimport re\n\n\nclass MultiProcessor:\n def __init__(self):\n self.args = self.parse_args()\n self.mode = self.args.mode\n self.root = Path(self.args.origin_dir)\n self.cpu_count = multiprocessing.cpu_count()\n self.multiplying_power = self.args.multiplying_power\n\n self.number = self.args.number\n self.weight_path = self.args.weight_path\n self.weight_map = io.loadmat(self.weight_path)['weightImgAll'][0][self.number] if self.number != -1 else None\n\n self.train_path = self.root / 'train' / 'images'\n self.test_path = self.root / 'test' / 'images'\n self.path_sets = [self.train_path, self.test_path]\n self.img_paths = [[], []]\n for phase, path in enumerate(self.path_sets):\n for img_path in path.glob('*.jpg'):\n self.img_paths[phase].append(str(img_path))\n self.present_phase = 0\n self.present_index = 0\n self.phase_list = ['train', 'test']\n self.save_dirs = [self.root / phase / 'amb_gt' for phase in self.phase_list]\n for save_dir in self.save_dirs:\n if not os.path.exists(str(save_dir)):\n os.makedirs(str(save_dir))\n\n self.log_path = self.root / 'log.json'\n if not self.log_path.exists():\n jpg_paths = self.train_path.glob('*.jpg')\n img_stem_example = jpg_paths.__next__().stem\n image_prefix = re.findall(r'(\\w+)_\\d+$', img_stem_example)[0] + '_'\n log_dict = {'multiplying_power': 1.5, 'image_prefix': image_prefix}\n with self.log_path.open(mode='w') as jsf:\n log_str = json.dumps(log_dict)\n jsf.write(log_str)\n print('json file created.')\n\n with self.log_path.open(mode='r') as jsf:\n log_dict = json.load(jsf)\n self.mp_match = (log_dict['multiplying_power'] == self.multiplying_power) if self.mode == 'amb' else None\n self.image_prefix = log_dict['image_prefix']\n\n self.threads = [threading.Thread(target=self.task, args=(i,)) for i in range(self.cpu_count)]\n print(f'count of threads: {self.cpu_count}')\n\n def task(self, processor_id):\n while True:\n if self.present_phase >= 2:\n return\n else:\n if self.present_index >= len(self.img_paths[self.present_phase]):\n self.present_phase += 1\n self.present_index = 0\n continue\n else:\n phase = self.present_phase\n index = self.present_index\n self.present_index += 1\n list_len = len(self.img_paths[phase])\n img_path = self.img_paths[phase][index]\n name = os.path.basename(img_path)\n print(f'thread {processor_id:<2}:phase[{phase+1}/2] image[{index+1}/{list_len}] '\n f'processing {img_path}')\n\n # mat = io.loadmat(\n # img_path.replace('.jpg', '.mat').replace('images', 'ground_truth')\n # .replace(self.image_prefix, 'GT_IMG_'))\n # points = mat[\"image_info\"][0][0][0][0][1] # 1546person*2(col,row)\n\n points = np.load(img_path.replace('.jpg', '.npy').replace('images', 'ground_truth')\n .replace(self.image_prefix, 'GT_IMG_'))\n\n img = plt.imread(img_path)\n # k = np.zeros((img.shape[0], img.shape[1]))\n\n k = self.gaussian_filter_density(img, points, self.multiplying_power, mode=self.mode)\\\n if self.number == -1 else \\\n self.weighted_density(img, points, self.weight_map, self.multiplying_power, mode=self.mode)\n # save density_map to disk\n im_save_path = str(self.save_dirs[phase] / name)\n gd_save_path = im_save_path.replace('jpg', 'npy')\n if self.mode == 'amb':\n # print('gd save path:', gd_save_path)\n np.save(gd_save_path, k)\n print(f'thread {processor_id:<2}: {gd_save_path} saved')\n else:\n h5_path = gd_save_path.replace('amb_gt', 'ground_truth').replace('.npy', '.h5')\n h5f = h5py.File(h5_path, 'w')\n h5f.create_dataset('density', data=k)\n h5f.close()\n print(f'thread {processor_id:<2}: {h5_path} saved')\n\n def start(self):\n if self.mode == 'amb':\n if self.mp_match:\n print('multiplying power matched.')\n return\n else:\n with self.log_path.open(mode='r') as jsf:\n log_dict = json.load(jsf)\n with self.log_path.open(mode='w') as jsf:\n log_dict['multiplying_power'] = 'changing'\n log_str = json.dumps(log_dict)\n jsf.write(log_str)\n\n for thread in self.threads:\n thread.setDaemon(True)\n thread.start()\n\n for thread in self.threads:\n thread.join()\n\n if self.mode == 'amb':\n with self.log_path.open(mode='r') as jsf:\n log_dict = json.load(jsf)\n with self.log_path.open(mode='w') as jsf:\n log_dict['multiplying_power'] = self.multiplying_power\n log_str = json.dumps(log_dict)\n jsf.write(log_str)\n\n print('done.')\n\n # partly borrowed from https://github.com/davideverona/deep-crowd-counting_crowdnet\n @staticmethod\n def gaussian_filter_density(img, points, multiplying_power, mode='gt'):\n '''\n This code use k-nearst, will take one minute or more to generate a density-map with one thousand people.\n\n points: a two-dimension list of pedestrians' annotation with the order [[col,row],[col,row],...].\n img_shape: the shape of the image, same as the shape of required density-map. (row,col). Note that can not have channel.\n\n return:\n density: the density-map we want. Same shape as input image but only has one channel.\n\n example:\n points: three pedestrians with annotation:[[163,53],[175,64],[189,74]].\n img_shape: (768,1024) 768 is row and 1024 is column.\n '''\n img_shape = [img.shape[0], img.shape[1]]\n # print(\"Shape of current image: \", img_shape, \". Totally need generate \", len(points), \"gaussian kernels.\")\n density = np.zeros(img_shape, dtype=np.float32)\n gt_count = len(points)\n if gt_count == 0:\n return density\n\n leafsize = 2048\n # build kdtree\n tree = KDTree(points.copy(), leafsize=leafsize)\n # query kdtree\n distances, locations = tree.query(points, k=4)\n\n # print('generate density...')\n for i, pt in enumerate(points):\n pt2d = np.zeros(img_shape, dtype=np.float32)\n if int(pt[1]) < img_shape[0] and int(pt[0]) < img_shape[1]:\n pt2d[int(pt[1]), int(pt[0])] = 1.\n else:\n continue\n if gt_count > 1:\n sigma = (distances[i][1] + distances[i][2] + distances[i][3]) * 0.1\n else:\n sigma = np.average(np.array(pt.shape)) / 2. / 2. # case: 1 point\n sigma = min(20., sigma)\n if mode == 'amb':\n sigma *= multiplying_power\n density += scipy.ndimage.filters.gaussian_filter(pt2d, sigma, mode='constant')\n # print('done.')\n density = np.clip(density, 0., 1.)\n return density\n\n @staticmethod\n def weighted_density(img, points, weight_map, multiplying_power, mode='gt'):\n img_shape = [img.shape[0], img.shape[1]]\n density = np.zeros(img_shape, dtype=np.float32)\n gt_count = len(points)\n if gt_count == 0:\n return density\n\n for i, pt in enumerate(points):\n pt2d = np.zeros(img_shape, dtype=np.float32)\n if int(pt[1]) < img_shape[0] and int(pt[0]) < img_shape[1]:\n pt2d[int(pt[1]), int(pt[0])] = 1.\n else:\n continue\n sigma = (1. / weight_map[pt[1]][pt[0]]) * 25\n if mode == 'amb':\n sigma *= multiplying_power\n density += scipy.ndimage.filters.gaussian_filter(pt2d, sigma, mode='constant')\n\n return density\n\n @staticmethod\n def parse_args():\n parser = argparse.ArgumentParser(description='Test ')\n parser.add_argument('origin_dir', default='/home/miaogen_pan/python_data/Shanghai/part_A_final',\n help='original data directory')\n parser.add_argument('-m', '--mode', type=str, default='gt', help='mode, amb or gt')\n parser.add_argument('-mp', '--multiplying_power', type=float, default=1.5, help='multiplying power of amb mode')\n parser.add_argument('-wp', '--weight_path', type=str, default='None', help='path of weight map')\n parser.add_argument('-n', '--number', type=int, default=-1, help='the number of weight map')\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n multi_processor = MultiProcessor()\n multi_processor.start()\n","repo_name":"tianhangpan/MFA","sub_path":"preprocess/make_gt.py","file_name":"make_gt.py","file_ext":"py","file_size_in_byte":9666,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"38983511900","text":"import torch\r\n\r\n#calculate kernel metrices\r\n#default RBF kernel\r\n\r\ndef kernel(X):\r\n sigma = 1\r\n A = X.T @ X\r\n d = torch.diag(A)\r\n B = d[:,None] + d[None,:] -2 * A\r\n B = -B / sigma**2\r\n K = torch.exp(B)\r\n return K\r\n","repo_name":"coder0505/FUFS","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22985355510","text":"size = int(input())\n\nmatrix = [[int(x) for x in input().split()] for row in range(size) ]\nbomb_index = [tuple(int(j) for j in i.split(',')) for i in input().split()]\nmatrix_copy = matrix.copy()\n\nbomb_damage_index = {\n 'up_left' : (-1,-1),\n 'up' : (-1,0),\n 'up_right' : (-1,1),\n 'left' : (0,-1),\n 'right' : (0,1),\n 'dwn_left' : (1,-1),\n 'dwn' : (1,0),\n 'dwn_right' : (1,1),\n}\n\nfor index in bomb_index:\n bomb_power = matrix[index[0]][index[1]]\n matrix_copy[index[0]][index[1]] -= bomb_power\n for key in bomb_damage_index:\n x = index[0] + bomb_damage_index[key][0]\n y = index[1] + bomb_damage_index[key][1]\n if 0 <= x < size and 0 <= y < size :\n if matrix_copy[x][y] > 0 :\n matrix_copy[x][y] -= bomb_power\n\nalive_cells = 0\nsum_of_cells = 0\n\nfor i in range(size):\n for j in range(size):\n if matrix_copy[i][j] > 0 :\n alive_cells += 1\n sum_of_cells += matrix_copy[i][j]\n\nprint(f'Alive cells: {alive_cells}')\nprint(f'Sum: {sum_of_cells}')\nfor row in matrix_copy:\n print(*row)\n\n","repo_name":"angelovang/Soft_Uni_problems_solutions","sub_path":"Advanced_09_2022/Advanced_Exer/Multidimencional_lists_1/bombs.py","file_name":"bombs.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41801730583","text":"import io\nimport csv\nimport pandas as pd\nimport absl\nimport tensorflow as tf\nimport contextlib2\nfrom object_detection.utils import dataset_util\nfrom object_detection.dataset_tools import tf_record_creation_util\n\n\"\"\"\nUsage:\npython create_tf_records.py --csv_input=dataset/test.csv --output_path=deep_learning/data/test.record\npython create_tf_records.py --csv_input=dataset/train.csv --output_path=deep_learning/data/train.record\n\n/home/elizarraras/.pyenv/versions/3.8.12/envs/tt/bin/python /home/elizarraras/Documents/Automated_Driller_Machine/deep_learning/create_tf_records.py --csv_input=dataset/processed_locations/test_good.csv --output_path=deep_learning/data2/test.record\n/home/elizarraras/.pyenv/versions/3.8.12/envs/tt/bin/python /home/elizarraras/Documents/Automated_Driller_Machine/deep_learning/create_tf_records.py --csv_input=dataset/processed_locations/train_good.csv --output_path=deep_learning/tfrecords_train/train.record\n\"\"\"\n\nflags = absl.flags\nflags.DEFINE_string('csv_input', '', 'Path to the CSV input')\nflags.DEFINE_string('output_path', '', 'Path to output TFRecord')\nFLAGS = flags.FLAGS\n\ndef create_tf_example(image_row):\n filename = image_row[0] # Filename of the image. Empty if image is not from file\n filename_path = \"dataset/all_good_images/\" + filename\n filename = filename.encode('utf8')\n with tf.io.gfile.GFile(filename_path, \"rb\") as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image_format = b'jpg'\n height, width = 640, 640 # Image height and width\n\n xmins = [] # List of normalized left x coordinates in bounding box (1 per box)\n xmaxs = [] # List of normalized right x coordinates in bounding box\n # (1 per box)\n ymins = [] # List of normalized top y coordinates in bounding box (1 per box)\n ymaxs = [] # List of normalized bottom y coordinates in bounding box\n # (1 per box)\n\n\n positions = [int(s) for s in image_row[1:] if s != \"\"]\n\n for i in range(0, len(positions), 4):\n xmins.append(positions[i] / width)\n ymins.append(positions[i+1] / width)\n xmaxs.append(positions[i+2] / width)\n ymaxs.append(positions[i+3] / width)\n\n tf_example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': dataset_util.int64_feature(height),\n 'image/width': dataset_util.int64_feature(width),\n 'image/filename': dataset_util.bytes_feature(filename),\n 'image/source_id': dataset_util.bytes_feature(filename),\n 'image/encoded': dataset_util.bytes_feature(encoded_jpg_io.read()),\n 'image/format': dataset_util.bytes_feature(image_format),\n 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),\n 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),\n 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),\n 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),\n }))\n return tf_example\n\n\ndef main(_):\n # writer = tf.io.TFRecordWriter(FLAGS.output_path)\n num_shards=10\n # output_filebase='/path/to/train_dataset.record'\n\n with contextlib2.ExitStack() as tf_record_close_stack:\n output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords(\n tf_record_close_stack, FLAGS.output_path, num_shards)\n with open(FLAGS.csv_input, \"r\") as r:\n reader = csv.reader(r)\n next(reader)\n for i, row in enumerate(reader):\n tf_example = create_tf_example(row)\n output_shard_index = i % num_shards\n output_tfrecords[output_shard_index].write(tf_example.SerializeToString())\n # writer.write(tf_example.SerializeToString())\n\n # writer.close()\n\nif __name__ == '__main__':\n absl.app.run(main)","repo_name":"gellanz/Automated_Driller_Machine","sub_path":"deep_learning/create_tf_records.py","file_name":"create_tf_records.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"6377048121","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic.base import RedirectView\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'project.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url('^$', RedirectView.as_view(url=\"/ospi/\"), name=\"home\"),\n url('^ospi/', include('project.ospi.urls')),\n url(r'^grappelli/', include('grappelli.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n","repo_name":"emmceemoore/ospi-website","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70743639639","text":"import numpy as np\nimport numba\nimport cmath\nimport math\n\nsigma_points = np.array([[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10]])\nincluded_positions = np.array([0, 1, 2])\ncoeffs = np.array([0.4, 0.3, 0.3, 0.5])\n\n@numba.jit(nopython=True)\ndef fast_log_ces_janos(sigma_points, coeffs, included_positions):\n \"\"\"Calculates the next period's predicted state of the latent factors' states. \n \n Args:\n * sigma_points: 2d array of sigma_points or states being transformed\n * coeffs: 1d array with coefficients specific to this transition function\n If the coeffs include an intercept term (e.g. the log of a TFP term),\n this has to be the FIRST or LAST element of coeffs.\n * included_positions: 1d array with the positions of the factors that are\n included in the transition equation \n\n Returns\n * 1d array\n \n \"\"\"\n nres = sigma_points.shape[0]\n phi = coeffs[-1]\n \n result = np.empty(nres)\n for i in range(nres):\n res = 0\n for pos in included_positions:\n res += coeffs[pos] * math.exp(sigma_points[i, pos] * phi)\n #res += coeffs[pos] * np.exp(sigma_points[i, pos] * phi)\n res = math.log(res) / phi\n #res = np.log(res) / phi\n result[i] = res\n\n return result\n \nresult = fast_log_ces_janos(sigma_points, coeffs, included_positions)\nprint(result)\n","repo_name":"lbaji/tasks_skillmodels","sub_path":"fast_log_CES_function_Janos.py","file_name":"fast_log_CES_function_Janos.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"395631201","text":"from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework import serializers\nfrom rest_framework.serializers import Serializer\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.hashers import check_password\n\nfrom rest_framework.authtoken.models import Token\n\nfrom .serializers import *\nfrom tienda.models import *\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom rest_framework.decorators import permission_classes\nfrom rest_framework.authentication import TokenAuthentication\n\nfrom rest_framework.permissions import IsAuthenticated\n\n# Create your views here.\n\n@csrf_exempt\n@api_view(['GET','POST'])\ndef listarProducto(request):\n\n if request.method == 'GET':\n listado = Producto.objects.all()\n Serializer = ProductoSerializers(listado, many=True)\n return Response(Serializer.data)\n\n elif request.method == 'POST':\n Serializer = ProductoSerializers(data= request.data)\n\n if Serializer.is_valid():\n Serializer.save()\n return Response(Serializer.data, status= status.HTTP_201_CREATED)\n return Response(Serializer.errors, status= status.HTTP_400_BAD_REQUEST) \n\n@csrf_exempt\n@api_view(['GET', 'DELETE' ,'PUT'])\ndef gestionarProducto(request, codigo_barra):\n\n try:\n objeto = Producto.objects.get(codigo_barra = codigo_barra)\n except Producto.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n Serializer = ProductoSerializers(objeto)\n return Response(Serializer.data)\n elif request.method == 'DELETE':\n objeto.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n elif request.method == 'PUT':\n Serializer = ProductoSerializers(objeto, data = request.data)\n\n if Serializer.is_valid():\n Serializer.save()\n return Response(Serializer.data)\n\n return Response(Serializer.errors, status= status.HTTP_400_BAD_REQUEST)\n\n@csrf_exempt\n@api_view(['GET','POST'])\n@permission_classes(IsAuthenticated,)\ndef listarUsuario(request):\n\n if request.method == 'GET':\n listado = Usuario.objects.all()\n Serializer = UsuarioSerializers(listado, many=True)\n return Response(Serializer.data)\n\n elif request.method == 'POST':\n Serializer = UsuarioSerializers(data= request.data)\n\n if Serializer.is_valid():\n Serializer.save()\n return Response(Serializer.data, status= status.HTTP_201_CREATED)\n return Response(Serializer.errors, status= status.HTTP_400_BAD_REQUEST) \n\n@csrf_exempt\n@api_view(['GET', 'DELETE' ,'PUT'])\n@permission_classes(IsAuthenticated,)\ndef gestionarUsuario(request, rut):\n\n try:\n objeto = Usuario.objects.get(rut = rut)\n except Producto.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n Serializer = UsuarioSerializers(objeto)\n return Response(Serializer.data)\n elif request.method == 'DELETE':\n objeto.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n elif request.method == 'PUT':\n Serializer = UsuarioSerializers(objeto, data = request.data)\n\n if Serializer.is_valid():\n Serializer.save()\n return Response(Serializer.data)\n\n return Response(Serializer.errors, status= status.HTTP_400_BAD_REQUEST)\n\n@csrf_exempt\n@api_view(['GET','POST'])\ndef listarProveedor(request):\n\n if request.method == 'GET':\n listado = Proveedor.objects.all()\n Serializer = ProveedorSerializers(listado, many=True)\n return Response(Serializer.data)\n\n elif request.method == 'POST':\n Serializer = ProveedorSerializers(data= request.data)\n\n if Serializer.is_valid():\n Serializer.save()\n return Response(Serializer.data, status= status.HTTP_201_CREATED)\n return Response(Serializer.errors, status= status.HTTP_400_BAD_REQUEST)\n\n@csrf_exempt\n@api_view(['GET', 'DELETE' ,'PUT'])\ndef gestionarProveedor(request, rut):\n\n try:\n objeto = Proveedor.objects.get(rut = rut)\n except Producto.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n Serializer = ProveedorSerializers(objeto)\n return Response(Serializer.data)\n elif request.method == 'DELETE':\n objeto.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n elif request.method == 'PUT':\n Serializer = ProveedorSerializers(objeto, data = request.data)\n\n if Serializer.is_valid():\n Serializer.save()\n return Response(Serializer.data)\n\n return Response(Serializer.errors, status= status.HTTP_400_BAD_REQUEST)\n\n\n\n\n\n\n\n@csrf_exempt\n@api_view(['POST'])\ndef login(request):\n if request.method == 'POST':\n username = request.POST = [\"username\"]\n password = request.POST =[\"password\"]\n\n try:\n usuario = User.objects.get(username = username)\n\n except User.DoesNotExist:\n return Response(\"Usuario no existe\")\n\n claveValida = check_password(password, usuario.password)\n\n if not claveValida:\n return Response(\"La clave no es valida\")\n\n token, created = Token.objects.get_or_create(user = usuario)\n\n return Response(token.key)","repo_name":"Moon3301/Repositorio_Ev3","sub_path":"entorno001/proyecto/restVentas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"91128746","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport scipy\nimport cmath\nimport math\nfrom scipy import optimize\nfrom scipy import special\nfrom scipy import misc\nimport shapely\nfrom shapely import geometry\nfrom shapely.geometry import LineString, Point\n\n# Solving the nondimensional dispersion relation by \n# Loiseleux et al. (1998, PoF).\n# The complex omega values are prescribed and determine\n# the complex beta; this is inserted into the dispersion\n# relation and its roots are found graphically in the complex plane.\n#\n# When no unstable growth rate is found, this is often tied\n# to the resolution of the D field, so increasing nmax usually\n# helps; also, omega_min and omega_max must cover the relevant domain\n# (omega_min may be negative in some cases). The present settings\n# work, but nmax, omega_min, and omega_max may need to be adjusted\n# if different azimuthal wavenumbers or axial wavenumbers are considered.\n#\n# Contact johannes.dahl@ttu.edu for questions.\n\n#------------------------------------------------\n# Set parameters\n#------------------------------------------------\n\nS = 1.0 # Swirl parameter\na = 0.0 # Co-flow parameter \n\n# m = 0\n# -----\n\n#m = 0 # Reproducing Loiseleux' plot (not used in teh MWR review paper)\n#kmax = 2.0\n#omega_max = 2.0\n#nmax = 1501\n#nnk = 21 # For how many k\n\n#m = +1\n#------\n\nS = 1.0\na = 0.0\nm = 1\nnmax = 601\nnnk = 31\nkmin = 0.001\nkmax = 5.0\n\nomega_min_r = 0.0\nomega_max_r = 4.0\nomega_min_i = 0.0\nomega_max_i = 8.0\n\n# m = -1 \n#-------\n\n#S = 1.0\n#a = 0.0\n#m = -1\n#nmax = 601\n#nnk = 31\n#kmin = 0.001\n#kmax = 5.0\n\n#omega_min_r = -5.0\n#omega_max_r = 5.0\n#omega_min_i = 0.0\n#omega_max_i = 5.0\n\n# To make sure the solver only picks unstable modes, omega_i must be larger than eps\n\neps = 0.001 # This value needs to be larger when nmax is reduced\n\n#-------------------------------------------------\n# Start\n#-------------------------------------------------\n\nnk = 0\n\nor_arr = np.zeros(nnk)\noi_arr = np.zeros(nnk)\nk_arr = np.zeros(nnk)\n\n\nfor k in np.linspace(kmin,kmax,nnk):\n\n\n print('STEP', nk, k) \n if (k == 0):\n k = 1.0E-12 # avoid k = 0\n\n # Initialize values of interest for complex omega\n\n fr2d = np.zeros(shape=(nmax,nmax))\n fi2d = np.zeros(shape=(nmax,nmax))\n\n counter = 0\n\n omega_r = np.linspace(omega_min_r, omega_max_r, nmax)\n omega_i = np.linspace(omega_min_i, omega_max_i, nmax) * 1j\n\n X, Y = np.meshgrid(omega_r, omega_i)\n\n Omega = X + Y # Not to be confused with the base state angular velocity, which does\n # not appear in the dimensionless formulation\n\n g = Omega - m*S - k\n beta = k * np.sqrt( (4.0*(S**2/g**2) - 1.0 ) )\n\n# Bessel function (1st kind) and its derivative\n\n bess = scipy.special.jv (m, beta)\n bess_der = scipy.special.jvp(m, beta)\n\n# Modified Bessel function (2nd kind) and its derivative\n\n mbess = scipy.special.kv (m, k)\n mbess_der = scipy.special.kvp(m, k)\n\n# Dispersion relation\n\n lhs = (g+k)**2 * ( beta * bess_der/(bess+1.0E-12) - 2.0*S*m/g )\n rhs = -g**2 * beta**2 / k * mbess_der/(mbess+1.0E-12) \n\n D = lhs - rhs\n\n fr2d = D.real\n fi2d = D.imag\n\n# Graphical solution (do not delete this part; C1 and C2 are used below)\n\n ox = np.linspace(omega_min_r, omega_max_r, nmax)\n oy = np.linspace(omega_min_i, omega_max_i, nmax)\n\n XX, YY = np.meshgrid(ox,oy)\n\n C1 = plt.contour(XX, YY, fr2d, levels = [0.0], linewidths = 2.0, colors = 'k')\n C2 = plt.contour(XX,YY, fi2d, levels = [0.0], linewidths = 2.0,colors = 'r')\n\n# This is not needed but interesting to look at\n\n plt.savefig(\"./dispersion_2d.png\", dpi=120)\n\n#---------------------------------------\n# Find intersection of zero-contours\n#---------------------------------------\n\n# Nested loops: Go through lines, then line segments of each plot\n\n aa = C1.allsegs[0]\n bb = C2.allsegs[0]\n\n# How many contours there are (some insersecting with the axes)\n\n ncts1 = len(aa) # number of \"blocks\" or pairs defining a contour in first plot\n ncts2 = len(bb)\n\n cc = 0\n px = np.zeros(100)\n py = np.zeros(100)\n\n for nc1 in np.arange(ncts1):\n\n # Number of data pairs of each line\n\n n1 = len(aa[nc1][:])\n\n arr1 = np.zeros(shape=(n1,2))\n\n for i in np.arange(n1):\n ar = aa[nc1][i]\n arr1[i,0] = ar[0]\n arr1[i,1] = ar[1]\n \n # Get arrays containing the coordinates of contour in second plot\n\n for nc2 in np.arange(ncts2):\n\n # Number of data pairs of each line\n\n n2 = len(bb[nc2][:])\n\n arr2 = np.zeros(shape=(n2,2))\n\n for j in np.arange(n2):\n ar = bb[nc2][j]\n arr2[j,0] = ar[0]\n arr2[j,1] = ar[1]\n\n# arr1[n,0], arr1[n,1] contains line segment starting and end points (of contour 1)\n\n for i in np.arange(n1-1): # Go through all segments of first line\n A = Point(arr1[i,0], arr1[i,1])\n B = Point(arr1[i+1,0], arr1[i+1,1])\n segm1 = LineString([A,B])\n \n for j in np.arange(n2-1): # Go through all segments of second line\n\n C = Point(arr2[j,0], arr2 [j, 1])\n D = Point(arr2[j+1,0], arr2[j+1,1])\n segm2 = LineString([C,D])\n\n # Find intersecting coordinates (all except one being empty)\n\n int_pt = segm1.intersection(segm2)\n\n # Find the nonzero intersection points\n\n if (not int_pt.is_empty):\n px[cc] = int_pt.x\n py[cc] = int_pt.y + 1.0E-12 # So that the max function works\n ppx = int_pt.x\n ppy = int_pt.y\n\n cc = cc + 1\n \n # Update the arrays, always using the max value\n \n maxindex = np.argmax(py)\n \n or_arr[nk] = px[maxindex]\n oi_arr[nk] = py[maxindex]\n\n if (ppy > eps): # Only pick the unstable mode (omega_i > 0) \n print('')\n print('S ', 'step ', 'm', 'k ', 'omega_r ', 'omega_i ', S, nk, m, k, ppx, ppy)\n print(px[maxindex],py[maxindex])\n\n nk = nk + 1\n##^\n\n#------------------------------------------------------------\n# Write/plot the dispersion relationship\n#------------------------------------------------------------\n\nk_arr = np.linspace(0.001,kmax,nnk)\n\nbeta_arr = np.zeros(nnk)\n\n# Write data to file:\n\nwith open('dispersion_relation_rankine_unstable.txt', 'w') as f:\n f.write('k (m-1) omega_r (s-1) omega_1 (s-1)\\n')\n\n for i in np.arange(nnk):\n\n wstr = str(k_arr[i])+' '+str(or_arr[i])+' '+str(oi_arr[i])+'\\n'\n f.write(wstr)\n print(k_arr[i], or_arr[i], oi_arr[i])\nf.close()\n\nplt.clf() # Somehow Python wants to plot the integrated previous figure\n\nplt.plot(k_arr, or_arr, 'k', linewidth = 2.0)\nplt.plot(k_arr, oi_arr, 'r', linewidth = 2.0)\n#plt.savefig(\"./dispersion.png\", dpi=120)\nplt.show()\n\n#------------------------------------------------------------\n# The End.\n#------------------------------------------------------------\n\n","repo_name":"joda80/vortex_waves","sub_path":"rankine_unstable_m1.py","file_name":"rankine_unstable_m1.py","file_ext":"py","file_size_in_byte":6757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18284174244","text":"#!/usr/bin/python3\n\"\"\"\n.PNG correcter\n\"\"\"\nfrom PIL import Image\nimport os\nimport math\n\ndef list_to_image(data, name, path, dimensions):\n array = [(\n data[i],\n data[i + 1],\n data[i + 2],\n data[i + 3]\n ) for i in range(0, len(data), 4)]\n im = Image.new('RGBA', (dimensions[0], dimensions[1]))\n im.putdata(array)\n if path == '':\n path = os.path.abspath(os.getcwd())\n filename = '{}{}'.format(\n path,\n name\n )\n print('Saving:', filename)\n im.save(filename)","repo_name":"Danucas/sol","sub_path":"api/v1/media/rgb.py","file_name":"rgb.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42336204159","text":"\"\"\"\n5.- El tiempo como tuplas.\n1. Proponer una representación con tuplas para representar el tiempo.\n2. Escribir una función sumaTiempo que reciba dos tiempos dados y devuelva\nsu suma.\n\"\"\"\n\ntiempo1 = (\"Horas\", 1, \"Minutos\", 5, \"Segundos\", 20)\ntiempo2 = (\"Horas\", 0, \"Minutos\", 10, \"Segundos\", 20)\nprint(tiempo1)\nprint(tiempo2)\nh1 = tiempo1[1]\nm1 = tiempo1[3] \ns1 = tiempo1[5]\nh2 = tiempo2[1]\nm2 = tiempo2[3] \ns2 = tiempo2[5]\n\ndef sumaTiempo(h1,h2,m1,m2,s1,s2):\n H3 = h1 + h2\n M3 = m1 + m2\n S3 = s1 + s2\n return H3, M3, S3\nresult = []\nresult = sumaTiempo(h1,h2,m1,m2,s1,s2)\nprint(result)\ntiempo3 = \"Horas: \", result[0], \"Minutos: \", result[1], \"Segundos: \", result[2]\nprint(tiempo3)\n\n","repo_name":"MauricioSerranoG/MauricioSerranoG-Curso_Python_Ejercicios_02_Datos_Copuestos","sub_path":"Datos_Compuestos-05.py","file_name":"Datos_Compuestos-05.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"25953170565","text":"from django.shortcuts import render\nfrom django.core.mail import send_mail\nfrom django.contrib.auth.models import Group, User\nfrom django.contrib.auth import authenticate, login\nfrom rest_framework import status\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes, renderer_classes\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom .models import Note, Tag, UserProfile\nfrom .serializers import NoteSerializer\nfrom datetime import datetime, timezone\n\n\n@api_view(['POST'])\n@renderer_classes([JSONRenderer])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef create_note(request):\n body = request.data\n keys = set(body.keys())\n\n if not {'name', 'text', 'video_link', 'audio_link'}.issubset(keys):\n return Response(\n {\n 'error': 'missing required parameters:[name, text, video_link, audio_link]'},\n status=status.HTTP_400_BAD_REQUEST)\n\n tags = None\n if 'tags' in keys:\n tags = body.pop(\"tags\")\n\n body['user'] = request.user\n new_note, note_created = Note.objects.get_or_create(**body)\n\n if note_created:\n new_note.accessed_at = new_note.created_at\n new_note.save()\n else:\n return Response({'message': 'note exists'}, status=status.HTTP_200_OK)\n\n if tags:\n for tag_name in tags:\n\n tag, created = Tag.objects.get_or_create(\n name=tag_name, user=request.user)\n if created:\n tag.accessed_at = tag.created_at\n else:\n tag.accessed_at = datetime.now(timezone.utc)\n\n tag.notes.add(new_note)\n\n serializer = NoteSerializer(new_note)\n\n return Response(\n serializer.data,\n status=status.HTTP_201_CREATED,\n content_type='application/json')\n\n\n@api_view(['POST'])\n@renderer_classes([JSONRenderer])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_note(request):\n body = request.data\n keys = set(body.keys())\n\n if not keys.issubset({'name', 'date', 'favorite'}):\n return Response(\n {\n 'error': 'missing required parameters:[name, date] or included extra parameters'},\n status=status.HTTP_400_BAD_REQUEST)\n\n note = Note.objects.filter(user=request.user)\n\n if 'favorite' in keys and body['favorite']:\n keys -= {'name', 'date'}\n note = note.filter(favorite=body['favorite']).order_by('-accessed_at')\n\n if 'name' in keys:\n note = note.filter(\n name__icontains=body['name']).order_by('-accessed_at')\n\n if 'date' in keys:\n oldest_time = datetime.strptime(body['date'], '%Y-%m-%dT%H:%M:%S.%fZ')\n note = note.filter(\n accessed_at__lte=oldest_time).order_by('-created_at')\n\n if not note.exists():\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n serializer = NoteSerializer(note, many=True)\n\n note.update(accessed_at=datetime.now(timezone.utc))\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n@api_view(['DELETE'])\n@renderer_classes([JSONRenderer])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef delete_note(request):\n body = request.data\n try:\n if isinstance(body['name'], list):\n current_note = Note.objects.filter(\n name__in=body['name'], user=request.user)\n else:\n current_note = Note.objects.filter(\n name=body['name'], user=request.user)\n current_note.delete()\n message = {'message': 'note deleted'}\n return Response(\n message,\n status=status.HTTP_200_OK,\n content_type='application/json')\n except KeyError:\n message = {\"error\": \" 'name' parameter not included\"}\n return Response(\n message,\n status=status.HTTP_400_BAD_REQUEST,\n content_type='application/json')\n\n\n@api_view(['POST'])\n@renderer_classes([JSONRenderer])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef update_note(request):\n body = request.data\n delete_tags = []\n add_tags = []\n keys = body.keys()\n if 'delete_tags' in keys:\n delete_tags = body.pop('delete_tags')\n if 'add_tags' in keys:\n add_tags = body.pop('add_tags')\n if 'current_name' in keys and 'new_name' in keys:\n current_name =body.pop('current_name')\n body['name'] = body.pop('new_name')\n else:\n current_name = body['name']\n try:\n body['accessed_at'] = datetime.now(timezone.utc)\n current_note = Note.objects.filter(\n name=current_name ,user=request.user)\n if not current_note.exists():\n return Response({'message': \"note does not exist\"},\n status=status.HTTP_200_OK)\n\n tags = Tag.objects.filter(\n user=request.user,\n name__in=delete_tags,\n notes=current_note[0])\n for tag in tags:\n tag.notes.remove(current_note[0])\n\n for tag_name in add_tags:\n tag, created = Tag.objects.get_or_create(\n name=tag_name, user=request.user)\n if created:\n tag.accessed_at = tag.created_at\n else:\n tag.accessed_at = datetime.now(timezone.utc)\n tag.notes.add(current_note[0])\n\n current_note.update(**body)\n current_note = Note.objects.filter(name=body['name'],user=request.user)\n serializer = NoteSerializer(current_note[0])\n\n return Response(\n serializer.data,\n status=status.HTTP_200_OK,\n content_type='application/json')\n except Note.DoesNotExist:\n message = {\"error\": \"note not found\"}\n return Response(\n message,\n status=status.HTTP_204_NO_CONTENT,\n content_type='application/json')\n except KeyError:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"jboakyedonkor/multimedia-notebook","sub_path":"backend/restapi/note_views.py","file_name":"note_views.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"73712671639","text":"from django.conf.urls import url\n\nfrom realtime.views import DriverCountView, LocationsView, OperatorCountView, DriverCountAntView, OperatorCountAntView\n\nurlpatterns = [\n url(r\"^driver_view/counter$\", DriverCountView.as_view()),\n url(r\"^driver_view/counter/ant$\", DriverCountAntView.as_view()),\n url(r\"^operator_view/locations$\", LocationsView.as_view()),\n url(r\"^operator_view/counter$\", OperatorCountView.as_view()),\n url(r\"^operator_view/counter/ant$\", OperatorCountAntView.as_view()),\n]\n","repo_name":"coder-baymax/taxi-poc-aws","sub_path":"poc-backend/realtime/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27569042969","text":"\nfrom tkinter import *\nfrom tkinter import messagebox\n# 一、create a root container\nroot =Tk(className='menu')\nroot.geometry('500x500+100+200')\n\n# 二、menu\n# a.scale\n# 1.create a label for showing the value of scale\nla1=Label(root,text='basket',bg='pink')\nla1.place(relx=0.4,rely=0.45)\n# 2.create a scale\ndef modifySize(value):\n newFont=('黑体',value)\n la1.config(font=newFont,text=f'basket\\nsize:{value}')\n# get value of scale via command.the scale will pass the value to command function\nsc1=Scale(root,from_=0,to=100,length=200,tickinterval=10,orient=HORIZONTAL,command=modifySize)\nsc1.place(relx=0.4,rely=0)\n# 三、loop\nroot.mainloop()","repo_name":"addpd904/pythonNote","sub_path":"GUI/scale.py","file_name":"scale.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34051611929","text":"import logging\nfrom pynput import keyboard # pynput, used to capture keyboard events\n\nlog_dir = \"/home/the-pratik/Desktop\" # variable stores the directory path where the log file will be saved\n\n# line configures the Python logging system\n# filename: Specifies the log file's location, combining the log_dir with the filename \"keyLog.txt.\"\n# level: Sets the logging level to DEBUG, which means that all log messages will be captured.\n# format: Specifies the log message format, including a timestamp and the actual log message.\nlogging.basicConfig(filename=log_dir + \"/keyLog.txt\", level=logging.DEBUG, format='%(asctime)s: %(message)s')\n\ndef on_press(key):\n logging.info(str(key)) # converts the key to a string and logs it\n\nlistener = keyboard.Listener(on_press=on_press) # creates an instance of keyboard.Listener and specifies the on_press function as the event handler for key presses\nlistener.start() # capturing keyboard events\nlistener.join() # line blocks the main thread and waits until the listener is stopped. listener runs in the background and processes keypress events\n","repo_name":"thepratiknidane/Keylogger","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71567421719","text":"import argparse\nimport cv2\n\n\ndef normalize(image):\n return (image - image.min()) / (image.max() - image.min())\n\n\ndef alpha_matte(foreground, background, alpha, output_path):\n F = normalize(cv2.imread(foreground))\n B = normalize(cv2.imread(background))\n a = normalize(cv2.imread(alpha))\n\n I = a * F + (1 - a) * B\n cv2.imwrite(output_path, I * 255)\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Blend images using Laplacian Pyramids or Laplacian Sequences.\")\n\n parser.add_argument(\n \"-f\",\n help=\"Path to the foreground image.\",\n required=True,\n type=str)\n\n parser.add_argument(\n \"-b\",\n help=\"Path to the background image to.\",\n required=True,\n type=str)\n\n parser.add_argument(\n \"-a\",\n help=\"Path to the alpha mask.\",\n required=True,\n type=str)\n\n parser.add_argument(\n \"-o\",\n help=\"Path where to save the matted image.\",\n default=\"matted.png\",\n type=str)\n\n args = parser.parse_args()\n alpha_matte(\n foreground=args.f,\n background=args.b,\n alpha=args.a,\n output_path=args.o\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"maikelroennau/alpha-matting","sub_path":"alpha_matting.py","file_name":"alpha_matting.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41994958735","text":"#zamiana temperatury\n# wejscie: \"35C\" \"100F\"\n# wyjscie: \"Temperatura w {typ} tp {xxx} stopni\"\n# C = (F - 32) * (5/9)\n# F = C * (9/5) + 32\n\n\ntemp = str(input(\"Podaj temperaturę: \")).upper()\n\nif temp.endswith(\"C\"):\n\n cel =temp[:-1]\n cel = int(cel)\n\n farh = cel * (9/5) + 32\n print(\"Temperatura w Farenhaitah to {} stopni\".format(farh))\n\n\n# sprawdzamy ostani znak\n# jesli C\n # obliczamy F\n # wypisujemy\nelif temp.endswith(\"F\"):\n farh = int(temp[0:-1])\n\n cel = (farh -32) * 5/9\n\n#jesli F\n #obliczamy C\n #wypisujemy\n print(\"Temperatura w Celciusza to {} stopni\".format(cel))\n\n","repo_name":"TomaszO81/Kursmm","sub_path":"pomoc/zadanie7.py","file_name":"zadanie7.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"36199477572","text":"import datetime\nimport math\nfrom matplotlib.figure import Figure\nfrom skyfield.api import Star, load, wgs84\nfrom skyfield.data import hipparcos\nfrom skyfield.api import utc\nfrom skyfield.projections import build_stereographic_projection\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom io import BytesIO\n\n\ndef create_map(lon, lat, time):\n\n lon = lon\n lat = lat\n time = load.timescale().utc(time)\n\n\n ''' configuring plot '''\n fig = Figure(figsize=(10,10), dpi=100, frameon=False)\n ax = fig.subplots(subplot_kw={'projection': 'polar'})\n ax.set_xticks([0, 0.25*math.pi, 0.5*math.pi, 0.75*math.pi, math.pi, 1.25*math.pi, 1.5*math.pi, 1.75*math.pi], ['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE'])\n ax.set_yticks([0.2, 0.4, 0.6, 0.8, 1], ['','','','',''])\n ax.tick_params(axis='x', colors='white')\n ax.spines['polar'].set_color('white')\n ax.yaxis.grid(False)\n ax.xaxis.grid(False)\n fig.set_facecolor((0,0,0))\n\n\n ''' loading astronomical data '''\n eph = load('de421.bsp')\n with load.open('hip_main.dat') as f:\n stars = hipparcos.load_dataframe(f)\n\n\n ''' setting observer and objects projection '''\n observer = wgs84.latlon(latitude_degrees=lat, longitude_degrees=lon).at(time)\n ra, dec, distance = observer.radec()\n center_object = Star(ra=ra, dec=dec)\n earth = eph['earth']\n center = earth.at(time).observe(center_object)\n projection = build_stereographic_projection(center)\n cartesian_to_polar = lambda x, y : (np.arctan2(y, x), np.sqrt(x**2 + y**2))\n\n\n ''' stars positions and sizes '''\n star_positions = earth.at(time).observe(Star.from_dataframe(stars))\n stars['x'], stars['y'] = projection(star_positions)\n stars['theta'], stars['radius'] = cartesian_to_polar(stars['x'], stars['y'])\n max_star_size = 30\n limiting_magnitude = 10\n bright_stars = (stars.magnitude <= limiting_magnitude)\n magnitude = stars['magnitude'][bright_stars]\n marker_size = max_star_size * 10 ** (magnitude / -3.5)\n ''' ploting stars '''\n ax.scatter(stars['theta'][bright_stars], stars['radius'][bright_stars], s=marker_size, color='white', marker='.', linewidths=0, zorder=2)\n\n\n ''' calculating positions and ploting other astronomical objects '''\n sun = eph['sun']\n sun_position = earth.at(time).observe(sun)\n sun_theta, sun_radius = cartesian_to_polar(projection(sun_position)[0], projection(sun_position)[1])\n ax.scatter(sun_theta, sun_radius, s=500, color='yellow', marker='.', linewidths=0, zorder=2)\n\n mercury = eph['MERCURY BARYCENTER']\n mercury_position = earth.at(time).observe(mercury)\n mercury_theta, mercury_radius = cartesian_to_polar(projection(mercury_position)[0], projection(mercury_position)[1])\n ax.scatter(mercury_theta, mercury_radius, s=70, color='brown', marker='.', linewidths=0, zorder=2)\n\n venus = eph['VENUS BARYCENTER']\n venus_position = earth.at(time).observe(venus)\n venus_theta, venus_radius = cartesian_to_polar(projection(venus_position)[0], projection(venus_position)[1])\n ax.scatter(venus_theta, venus_radius, s=70, color=(200/255,120/255,30/255), marker='.', linewidths=0, zorder=2)\n\n mars = eph['MARS BARYCENTER']\n mars_position = earth.at(time).observe(mars)\n mars_theta, mars_radius = cartesian_to_polar(projection(mars_position)[0], projection(mars_position)[1])\n ax.scatter(mars_theta, mars_radius, s=70, color=(220/255,60/255,30/255), marker='.', linewidths=0, zorder=2)\n\n jupiter = eph['JUPITER BARYCENTER']\n jupiter_position = earth.at(time).observe(jupiter)\n jupiter_theta, jupiter_radius = cartesian_to_polar(projection(jupiter_position)[0], projection(jupiter_position)[1])\n ax.scatter(jupiter_theta, jupiter_radius, s=70, color=(145/255,100/255,30/255), marker='.', linewidths=0, zorder=2)\n\n saturn = eph['SATURN BARYCENTER']\n saturn_position = earth.at(time).observe(saturn)\n saturn_theta, saturn_radius = cartesian_to_polar(projection(saturn_position)[0], projection(saturn_position)[1])\n ax.scatter(saturn_theta, saturn_radius, s=70, color=(190/255,150/255,50/255), marker='.', linewidths=0, zorder=2)\n\n uranus = eph['URANUS BARYCENTER']\n uranus_position = earth.at(time).observe(uranus)\n uranus_theta, uranus_radius = cartesian_to_polar(projection(uranus_position)[0], projection(uranus_position)[1])\n ax.scatter(uranus_theta, uranus_radius, s=70, color=(60/255,220/255,200/255), marker='.', linewidths=0, zorder=2)\n\n neptune = eph['NEPTUNE BARYCENTER']\n neptune_position = earth.at(time).observe(neptune)\n neptune_theta, neptune_radius = cartesian_to_polar(projection(neptune_position)[0], projection(neptune_position)[1])\n ax.scatter(neptune_theta, neptune_radius, s=70, color=(35/255,70/255,220/255), marker='.', linewidths=0, zorder=2)\n\n moon = eph['moon']\n moon_position = earth.at(time).observe(moon)\n moon_theta, moon_radius = cartesian_to_polar(projection(moon_position)[0], projection(moon_position)[1])\n ax.scatter(moon_theta, moon_radius, s=70, color=(75/255,75/255,75/255), marker='.', linewidths=0, zorder=2)\n\n ax.set_rmax(1)\n ax.set_rmin(0)\n\n bckg = plt.Circle((0, 0), 4, color='black', fill=True)\n ax.add_patch(bckg)\n\n tmpfile = BytesIO()\n fig.savefig(tmpfile, format='png')\n return tmpfile\n","repo_name":"witek3100/sky-map","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73483872596","text":"import requests\nurl = \"https://umku10.tistory.com/6\"\n# headers에 user agent 정의\n# user agent는 what is my user agent 검색\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36\"}\nres = requests.get(url, headers=headers)\nres.raise_for_status()\n\nprint(len(res.text))\n","repo_name":"Gun1Yun/Joaad-Add","sub_path":"Study/02_user_agent.py","file_name":"02_user_agent.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19237798075","text":"from baseParser import BaseParser\n\nclass ParserSnellsLaw(BaseParser):\n def __init__(self):\n self.parseFilename = \"snells/S_IF\"\n self.parseSplitToken = \"________________________________________________________________________________\"\n self.outputFilename = \"resultsSnellsLaw.csv\"\n\n self.varNameInputList = [\"H1\", \"T\", \"d1\", \"Alpha1\",\\\n \"COTAN NS Slope\", \"d2\"]\n self.varNameOutputList = [\"H1\", \"H0\", \"H2\", \"Alpha1\", \"Alpha0\", \"Alpha2\",\\\n \"L1\", \" L0\", \"L2\", \"C1\", \"C0\", \"C2\", \"Cg1\", \"Cg0\", \"Cg2\",\\\n \"E1\", \"E0\", \"E2\", \"P1\", \"P0\", \"P2\", \"U1\", \"U2\",\\\n \"H0/L0\", \"Hb\", \"db\"]\n\n super(ParserSnellsLaw, self).__init__()\n # end __init__\n\nparser = ParserSnellsLaw()","repo_name":"allthroughthenight/aces","sub_path":"misc/parser/parserSnellsLaw.py","file_name":"parserSnellsLaw.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31696444373","text":"import torch\nimport pickle\nfrom sklearn.metrics.pairwise import pairwise_distances\nimport numpy as np\nimport torch.nn.functional as F\n\n\ndef calculate_isotropic_covariance(pos):\n assert len(pos.shape) == 2\n assert pos.shape[1] == 3\n mu = pos.mean(axis=0, keepdims=True)\n pos = pos - mu # pos [N,3]\n pos = pos.reshape(-1, 1)\n M = pos.shape[0]\n covariance = np.matmul(pos.T, pos)\n covariance = covariance / M * np.eye(3)\n return covariance\n\n\ndef calcula_anisotropic_covariance(pos):\n assert len(pos.shape) == 2\n assert pos.shape[1] == 3\n mu = pos.mean(axis=0, keepdims=True)\n pos = pos - mu # pos [N,3]\n N = pos.shape[0]\n covariance = np.matmul(pos.T, pos)\n covariance = covariance / N\n return covariance\n\n\ndef get_iso_aniso_mu_cov(pos):\n if pos.shape[0] == 0:\n iso_mu = np.zeros_like(pos)\n iso_cov = np.eye(0)\n aniso_mu = np.zeros_like(pos)\n aniso_cov = np.eye(0)\n else:\n iso_mu = aniso_mu = pos.mean(axis=0)\n iso_cov = calculate_isotropic_covariance(pos)\n aniso_cov = calcula_anisotropic_covariance(pos)\n return iso_mu, iso_cov, aniso_mu, aniso_cov\n\n\ndef substitute_golden_prior_with_beta_prior(data, beta_prior_path, protein_ligand_dist_th=10.0):\n beta_prior = pickle.load(open(beta_prior_path, 'rb'))\n data.num_arms = len(beta_prior['arms_prior'])\n data.num_scaffold = len(beta_prior['scaffold_prior'])\n assert data.num_arms == beta_prior['num_arms']\n assert data.num_scaffold == beta_prior['num_scaffold']\n\n data.arms_prior = []\n data.scaffold_prior = []\n data.pocket_atom_masks = []\n for arms_prior in beta_prior['arms_prior']:\n num, mu_i, cov_i, mu_a, cov_a = arms_prior\n data.arms_prior.append((num, torch.tensor(mu_i).float(), torch.tensor(cov_i).float(), None, None))\n mu_i = torch.tensor(mu_i).float().reshape(1, 3)\n dist = pairwise_distances(mu_i, data.protein_pos).reshape(-1)\n mask = dist < protein_ligand_dist_th\n data.pocket_atom_masks.append(mask)\n if len(beta_prior['scaffold_prior']) == 1:\n num, mu_i, cov_i, mu_a, cov_a = beta_prior['scaffold_prior'][0]\n data.scaffold_prior.append((num, torch.tensor(mu_i).float(), torch.tensor(cov_i).float(), None, None))\n data.pocket_atom_masks = torch.tensor(data.pocket_atom_masks)\n\n\ndef substitute_golden_prior_with_given_prior(data, prior_dict, protein_ligand_dist_th=10.0):\n data.num_arms = len(prior_dict['arms_prior'])\n data.num_scaffold = len(prior_dict['scaffold_prior'])\n assert len(prior_dict['scaffold_prior']) <= 1\n\n data.arms_prior = []\n data.scaffold_prior = []\n data.pocket_atom_masks = []\n for arms_prior in prior_dict['arms_prior']:\n num, mu_i, cov_i, mu_a, cov_a = arms_prior\n data.arms_prior.append((num, torch.tensor(mu_i).float(), torch.tensor(cov_i).float(), None, None))\n mu_i = torch.tensor(mu_i).float().reshape(1, 3)\n dist = pairwise_distances(mu_i, data.protein_pos).reshape(-1)\n mask = dist < protein_ligand_dist_th\n data.pocket_atom_masks.append(mask)\n if len(prior_dict['scaffold_prior']) == 1:\n num, mu_i, cov_i, mu_a, cov_a = prior_dict['scaffold_prior'][0]\n data.scaffold_prior.append((num, torch.tensor(mu_i).float(), torch.tensor(cov_i).float(), None, None))\n data.pocket_atom_masks = torch.tensor(data.pocket_atom_masks)\n\n\ndef apply_std_coef(data, std_coef):\n new_arms_prior = []\n for arm_prior in data.arms_prior:\n num, mu_i, cov_i, _, _ = arm_prior\n cov_i *= std_coef ** 2\n new_arms_prior.append((num, mu_i, cov_i, None, None))\n data.arms_prior = new_arms_prior\n new_scaffold_prior = []\n if len(data.scaffold_prior) > 0:\n assert len(data.scaffold_prior) == 1\n num, mu_i, cov_i, _, _ = data.scaffold_prior[0]\n cov_i *= std_coef ** 2\n new_scaffold_prior.append((num, mu_i, cov_i, None, None))\n data.scaffold_prior = new_scaffold_prior\n\n\ndef apply_num_atoms_change(data, num_atoms_change):\n new_arms_prior = []\n for arm_prior in data.arms_prior:\n num, mu_i, cov_i, _, _ = arm_prior\n num += num_atoms_change\n num = max(num, 1)\n new_arms_prior.append((num, mu_i, cov_i, None, None))\n data.arms_prior = new_arms_prior\n new_scaffold_prior = []\n if len(data.scaffold_prior) > 0:\n assert len(data.scaffold_prior) == 1\n num, mu_i, cov_i, _, _ = data.scaffold_prior[0]\n num += num_atoms_change\n num = max(num, 1)\n new_scaffold_prior.append((num, mu_i, cov_i, None, None))\n data.scaffold_prior = new_scaffold_prior\n\n\ndef compute_golden_prior_from_data(data):\n # add prior\n pocket_prior_masks = []\n pocket_prior_contact_threshold = 6.0\n # >>> arms\n arms_prior = []\n for arm_id in range(data.num_arms):\n arm_atom_pos = data.ligand_pos[data.ligand_atom_mask == arm_id, :]\n (arm_iso_mu, arm_iso_cov, arm_aniso_mu, arm_aniso_cov) = get_iso_aniso_mu_cov(arm_atom_pos)\n arm_atom_num = arm_atom_pos.shape[0]\n arms_prior.append((arm_atom_num, arm_iso_mu, arm_iso_cov, arm_aniso_mu, arm_aniso_cov))\n cdist = F.pairwise_distance(arm_iso_mu.unsqueeze(0), data.protein_pos)\n cmask = cdist < pocket_prior_contact_threshold\n pocket_prior_masks.append(cmask)\n # >>> scaffold\n scaffold_prior = []\n scaffold_atom_pos = data.ligand_pos[data.ligand_atom_mask == -1, :]\n (scaffold_iso_mu, scaffold_iso_cov, scaffold_aniso_mu,\n scaffold_aniso_cov) = get_iso_aniso_mu_cov(scaffold_atom_pos)\n scaffold_atom_num = scaffold_atom_pos.shape[0]\n if scaffold_atom_num > 0:\n scaffold_prior.append((scaffold_atom_num, scaffold_iso_mu, scaffold_iso_cov,\n scaffold_aniso_mu, scaffold_aniso_cov))\n cdist = F.pairwise_distance(scaffold_iso_mu.unsqueeze(0), data.protein_pos)\n cmask = (cdist < pocket_prior_contact_threshold).bool()\n pocket_prior_masks.append(cmask)\n\n data.scaffold_prior = scaffold_prior\n data.arms_prior = arms_prior\n assert len(data.arms_prior) == data.num_arms\n assert len(data.scaffold_prior) == data.num_scaffold\n data.pocket_prior_masks = torch.stack(pocket_prior_masks)\n assert len(data.pocket_prior_masks) == data.num_arms + data.num_scaffold\n return data\n\n\nclass NumAtomsSampler():\n def __init__(self, pred_models_dict):\n super().__init__()\n self.arm_model = pred_models_dict['arm_model']\n self.armstd_model = pred_models_dict['armstd_model']\n self.sca_model = pred_models_dict['sca_model']\n self.scastd_model = pred_models_dict['scastd_model']\n\n def sample_arm_natoms(self, arm_centers, protein_pos):\n pair_distance = torch.norm(arm_centers.view(-1, 1, 3) - protein_pos.view(1, -1, 3), p=2, dim=-1)\n p_natoms = torch.stack([(pair_distance < r).sum(1) for r in np.linspace(1, 10, 50)], dim=1)\n x = p_natoms.numpy()\n y = self.arm_model.predict(x)\n # print('arm n atom prediction: ', y)\n arm_natoms = self.sample_natoms_from_prediction(y, std=0.2)\n arm_stds = self.armstd_model.predict(arm_natoms[:, None])\n arm_natoms = arm_natoms.tolist()\n arm_stds = torch.from_numpy(arm_stds.astype(np.float32)).reshape(-1, 1).expand(-1, 3)\n return arm_natoms, arm_stds\n\n def sample_sca_natoms(self, sca_center, arm_centers, arm_stds, protein_pos):\n pair_distance = torch.norm(sca_center.view(-1, 1, 3) - protein_pos.view(1, -1, 3), p=2, dim=-1)\n p_natoms = torch.stack([(pair_distance < r).sum(1) for r in np.linspace(1, 10, 50)], dim=1)\n\n armsca_distances = torch.norm(sca_center.view(-1, 1, 3) - arm_centers.view(1, -1, 3), p=2, dim=-1).numpy()\n # print('armsca_distances: ', armsca_distances)\n armsca_res = [d - r for d, r in zip(armsca_distances, arm_stds.numpy())]\n\n p_natoms_feat = p_natoms.numpy()\n # print(p_natoms_feat.shape)\n dist_feat = np.array([d.sum() for d in armsca_res])\n # print(dist_feat.shape)\n\n x = np.concatenate([p_natoms_feat, dist_feat[:, None]], axis=-1)\n y = self.sca_model.predict(x)\n # print('x shape: ', x.shape, y.shape)\n sca_natoms = self.sample_natoms_from_prediction(y, std=0.)\n sca_stds = self.scastd_model.predict(sca_natoms[:, None])\n assert len(sca_natoms) == len(sca_stds) == 1\n sca_natoms = sca_natoms.tolist()[0]\n sca_stds = torch.from_numpy(sca_stds.astype(np.float32)).expand(3)\n return sca_natoms, sca_stds\n\n def sample_natoms_from_prediction(self, n, std, min_natoms=2):\n natoms = np.ceil(n + std * n * np.random.randn(len(n))).astype(int)\n natoms = np.maximum(natoms, min_natoms)\n return natoms\n","repo_name":"bytedance/DecompDiff","sub_path":"utils/prior.py","file_name":"prior.py","file_ext":"py","file_size_in_byte":8761,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"85"} +{"seq_id":"73142167317","text":"#!/usr/bin/env python\n\nfrom ctypes import c_int, pointer, POINTER, sizeof, c_char, c_uint8, c_int16, cast\nfrom pyogg import opus\nfrom pyogg.opus import opus_int16, opus_int16_p, c_uchar\n\nimport array\nimport functools\nimport operator\nimport pyaudio\nimport queue\nimport sys\nimport time\nimport wave\n\nstatusvals = [ 'paInputUnderflow', 'paInputOverflow', 'paOutputUnderflow', 'paOutputOverflow', 'paPrimingOutput' ]\nstatuses = { getattr(pyaudio, y): y for y in statusvals }\n\ndef printstatus(x):\n\tr = []\n\twhile x:\n\t\tb = x & -x\t# get a single bit\n\t\tr.append(statuses[b])\n\t\tx &= ~b\t\t# clear the bit we added\n\n\treturn ', '.join(r)\n\nrate = 48000\nframelength = .0025\nmaxbw = 128*1024\nsampperframe = int(framelength * rate) # 5ms latency\n\npa = pyaudio.PyAudio()\n\nfor i in range(pa.get_device_count()):\n\tprint(i, repr(pa.get_device_info_by_index(i)))\n\n#sys.exit(0)\nclass _OpusBase(object):\n\t@staticmethod\n\tdef _check_err(err):\n\t\tif err != opus.OPUS_OK:\n\t\t\traise RuntimeError('failed', err)\n\nclass OpusDecoder(_OpusBase):\n\tdef __init__(self, rate, nchan):\n\t\terr = c_int()\n\t\tself._nchan = nchan\n\t\tself._bytespersamp = nchan * sizeof(opus.opus_int16)\n\t\t#print('foo:', repr((self._bytespersamp, nchan, sizeof(opus.opus_int16))))\n\t\tself._pcmbuf = (opus_int16 * (nchan * int(rate * framelength)))()\n\t\tself._dec = opus.opus_decoder_create(rate, nchan, pointer(err))\n\t\tself._check_err(err.value)\n\n\tdef decode(self, frm):\n\t\t#print(repr(frm))\n\t\tr = opus.opus_decode(self._dec, cast(frm, POINTER(c_uchar)), len(frm), self._pcmbuf, len(self._pcmbuf), 0)\n\t\tif r < 0:\n\t\t\tself._check_err(r)\n\n\t\treturn array.array('h', self._pcmbuf[:self._nchan * r]).tobytes()\n\n\tdef __del__(self):\n\t\topus.opus_decoder_destroy(self._dec)\n\t\tself._dec = None\n\nclass OpusEncoder(_OpusBase):\n\tdef __init__(self, rate, nchan, app):\n\t\terr = c_int()\n\t\tself._nchan = nchan\n\t\tself._bytespersamp = nchan * sizeof(opus.opus_int16)\n\t\t#print('bar:', repr((self._bytespersamp, nchan, sizeof(opus.opus_int16))))\n\t\tself._frbuf = (c_char * (self._bytespersamp * int(maxbw * framelength)))()\n\t\tself._enc = opus.opus_encoder_create(rate, nchan, app, pointer(err))\n\t\tself._check_err(err.value)\n\n\tdef get_max_bw(self):\n\t\tval = opus.opus_int32()\n\t\tr = opus.opus_encoder_ctl(self._enc, opus.OPUS_GET_MAX_BANDWIDTH, pointer(val))\n\t\tself._check_err(r)\n\t\treturn val.value\n\n\tdef set_max_bw(self, maxbw):\n\t\tr = opus.opus_encoder_ctl(self._enc, opus.OPUS_SET_MAX_BANDWIDTH, opus.opus_int32(maxbw))\n\t\tself._check_err(r)\n\n\tdef get_inband_fec(self):\n\t\tval = opus.opus_int32()\n\t\tr = opus.opus_encoder_ctl(self._enc, opus.OPUS_GET_INBAND_FEC_REQUEST, pointer(val))\n\t\tself._check_err(r)\n\t\treturn val.value\n\n\tdef set_inband_fec(self, maxbw):\n\t\tr = opus.opus_encoder_ctl(self._enc, opus.OPUS_SET_INBAND_FEC_REQUEST, opus.opus_int32(maxbw))\n\t\tself._check_err(r)\n\n\tdef get_pkt_loss(self):\n\t\tval = opus.opus_int32()\n\t\tr = opus.opus_encoder_ctl(self._enc, opus.OPUS_GET_PACKET_LOSS_PERC_REQUEST, pointer(val))\n\t\tself._check_err(r)\n\t\treturn val.value\n\n\tdef set_pkt_loss(self, percent):\n\t\tr = opus.opus_encoder_ctl(self._enc, opus.OPUS_SET_PACKET_LOSS_PERC_REQUEST, opus.opus_int32(percent))\n\t\tself._check_err(r)\n\n\tdef encode(self, pcm):\n\t\tfs = len(pcm) // self._bytespersamp\n\t\t#print(repr(pcm), fs, repr(opus_int16_p), repr(self._nchan))\n\t\t#print('baz:', fs, repr((len(pcm), self._bytespersamp)))\n\t\tr = opus.opus_encode(self._enc, cast(pcm, opus_int16_p), fs, cast(self._frbuf, POINTER(c_uchar)), len(self._frbuf))\n\t\t#r = opus.opus_encode(self._enc, pcm, fs, self._frbuf, len(self._frbuf))\n\t\tif r < 0:\n\t\t\tself._check_err(r)\n\n\t\t#print(repr(self._frbuf), dir(self._frbuf))\n\t\treturn self._frbuf.raw[:r]\n\n\tdef __del__(self):\n\t\topus.opus_encoder_destroy(self._enc)\n\t\tself._enc = None\n\nenc = OpusEncoder(rate, 1, opus.OPUS_APPLICATION_RESTRICTED_LOWDELAY)\ndec = OpusDecoder(rate, 1)\n\nenc.set_inband_fec(1)\nenc.set_pkt_loss(5)\nprint('pl:', repr(enc.get_pkt_loss()))\nprint('if:', repr(enc.get_inband_fec()))\n\n#sys.exit(0)\n\ninbuffer = queue.Queue()\noutbufferinfo = []\noutbuffer = []\nadcdiff = []\ndacdiff = []\nadcdacdiff = []\n\ntimes = []\n\ndef excprinter(func):\n\t@functools.wraps(func)\n\tdef func_wrapper(*args, **kwargs):\n\t\tglobal times\n\t\ttry:\n\t\t\ts = time.time()\n\t\t\tr = func(*args, **kwargs)\n\t\t\ttimes.append((s, time.time()))\n\t\texcept:\n\t\t\timport traceback\n\t\t\ttraceback.print_exc()\n\t\t\traise\n\n\t\treturn r\n\n\treturn func_wrapper\n\n#wf = wave.open('foo.wav', 'wb')\n#wf.setnchannels(1)\n#wf.setsampwidth(2)\n#wf.setframerate(rate)\n\ncnt = 0\nstarttime = None\ncombstatus = 0\n\n@excprinter\ndef incallback(in_data, frm_cnt, timeinfo, status):\n\tinbuffer.put((in_data, frm_cnt, timeinfo, status))\n\n\tif time.time() - s < 5:\n\t\treturn ('', pyaudio.paContinue)\n\n\tinbuffer.put(None)\t# signal finished\n\treturn ('', pyaudio.paComplete)\n\ndef outcallback(in_data, frm_cnt, timeinfo, status):\n\toutbufferinfo.append((in_data, frm_cnt, timeinfo, status))\n\n\tif outbuffer:\n\t\tbuf = outbuffer.pop(0)\n\telse:\n\t\tbuf = '\\x00\\x00' * sampperframe\n\n\tif buf is None:\n\t\treturn (dbuf, pyaudio.paComplete)\n\n\treturn (buf, pyaudio.paContinue)\n\ninstream = pa.open(rate=rate, channels=1, format=pyaudio.paInt16, input_device_index=0, input=True, frames_per_buffer=sampperframe, stream_callback=incallback)\noutstream = pa.open(rate=rate, channels=1, format=pyaudio.paInt16, output_device_index=3, output=True, frames_per_buffer=sampperframe, stream_callback=outcallback)\nprint('il:', instream.get_input_latency())\nprint('ol:', outstream.get_output_latency())\n\ns = time.time()\n\nprint('starting')\ninstream.start_stream()\noutstream.start_stream()\nwhile True:\n\t#print('sleep')\n\td = inbuffer.get()\n\tif d is None:\n\t\tbreak\n\tin_data, frm_cnt, timeinfo, status = d\n\n\tcombstatus |= status\n\tif starttime is None:\n\t\tstarttime = timeinfo\n\tlasttime = timeinfo\n\n\t#print('pcb:', repr((type(in_data), len(in_data), frm_cnt, timeinfo, status)))\n\tadcdiff.append(timeinfo['current_time'] - timeinfo['input_buffer_adc_time'])\n\tdacdiff.append(timeinfo['output_buffer_dac_time'] - timeinfo['current_time'])\n\tadcdacdiff.append(timeinfo['output_buffer_dac_time'] - timeinfo['input_buffer_adc_time'])\n\tcnt += len(in_data)\n\t#buf = enc.encode(in_data)\n\tbuf = in_data\n\t#print('r:', len(buf), repr(buf), repr(type(buf)))\n\toutbuffer.append(buf)\n\ninstream.stop_stream()\noutstream.stop_stream()\ninstream.close()\noutstream.close()\nprint('done')\n\n#print(repr(adcdiff))\n#print(repr(dacdiff))\nprint(max(adcdacdiff), min(adcdacdiff))\nprint(cnt)\nprint(starttime)\nprint(outbufferinfo[0][2])\nprint(lasttime)\nprint(outbufferinfo[-1][2])\nprint(lasttime['current_time'] - starttime['current_time'])\nprint('in status:', printstatus(combstatus))\nprint('out status:', printstatus(functools.reduce(operator.__or__, (x[3] for x in outbufferinfo), 0)))\nltimes = [ (e - s) * 1000 for s, e in times ]\nprint(min(ltimes), max(ltimes))\npa.terminate()\n","repo_name":"dumblob/jamming","sub_path":"purepy/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23550704827","text":"from django.shortcuts import render, redirect\nfrom pytube import *\nfrom django.contrib import messages\n\n# Create View\ndef youtube(request):\n # checking whether request.method is post or not\n if request.method == 'POST':\n # getting link from frontend\n link = request.POST['link']\n video = YouTube(link)\n # setting video resolution\n stream = video.streams.get_highest_resolution()\n # downloads video\n stream.download()\n messages.success(request, 'Download Successfully!')\n # returning HTML page\n return render(request, 'youtube.html')\n return render(request, 'youtube.html')","repo_name":"cleason/youtube_download","sub_path":"youtubeApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7326666373","text":"from grandpybot.utils.parser import Parser\nimport pytest\n\n\nclass TestParser:\n\n def setup_method(self):\n self.test_parser = Parser()\n self.raw_text = (\n \"Salut GrandPy ! Par hasard, est-ce que tu connais\"\n \" l'adresse d'OpenClassrooms ?\")\n self.sentence = \"Est-ce que tu connais l'adresse d'OpenClassrooms ?\"\n\n def test_raw_to_sentences(self):\n assert len(\n self.test_parser.raw_to_sentences(self.raw_text)) == 3\n assert self.test_parser.raw_to_sentences(\n self.raw_text)[0] == \"Salut GrandPy !\"\n assert self.test_parser.raw_to_sentences(\n self.raw_text)[1] == \"Par hasard\"\n assert self.test_parser.raw_to_sentences(\n self.raw_text)[2] == (\n \"est-ce que tu connais l'adresse d'OpenClassrooms ?\")\n\n def test_get_keywords(self):\n keywords = \\\n [w.lower() for w in self.test_parser.get_keywords(self.sentence)]\n assert keywords == [\"connais\", \"adresse\", \"openclassrooms\"]\n","repo_name":"loictessier/GrandPy-Bot","sub_path":"grandpybot/tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71649210197","text":"from keras.models import load_model\nfrom PIL import Image\nimport tensorflow.lite as tflite\n\nfrom loss import gradient_importance\nfrom datagen import datagen\n\ntarget_size=(256, 256)\nsource_rescale=(56, 56)\nbatch_size=6\n\npath = '/home/gbentor/OpenUni/DataScience/de-pixalize/data/.fr-GYFAt4/real_vs_fake/real-vs-fake/small_test'\n# path = '../../../data/test'\ntest_generator = datagen(path, source_rescale, target_size, batch_size, shuffle=False)\n\nX, y = next(test_generator)\n\nmodel = load_model('saved_models/model_laplace.h5', custom_objects={'gradient_importance': gradient_importance})\n\npredicted = model.predict(X, batch_size=batch_size)\n\nfor i in range(batch_size):\n\tp_im = Image.fromarray(predicted[i].reshape(*target_size)*255).convert('RGB')\n\tX_im = Image.fromarray(X[i].reshape(*target_size)*255).convert('RGB')\n\ty_im = Image.fromarray(y[i].reshape(*target_size)*255).convert('RGB')\n\tp_im.save('images/p_{}.png'.format(i+1))\n\tX_im.save('images/X_{}.png'.format(i+1))\n\ty_im.save('images/y_{}.png'.format(i+1))","repo_name":"gbentor/image-depixelizer","sub_path":"src/orig_predict.py","file_name":"orig_predict.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"42262842389","text":"\"\"\"\nRohan Dalal\n25 March 2021\nIDT\n1st Period\nSMF_18\n\"\"\"\n# I imported the module, and other libraries\nimport SMF_18_module\nimport os, sys\nimport cs50\nimport time\n\ndef main():\n #Here the function is used with a wait time to simulate thinking\n geom = SMF_18_module.inf_geom_series\n response = input('Would you like to do a calculation of an infinite geom series, say \"yes\" or \"no\" ')\n if(response == 'yes'):\n a = float(input('What is the first term'))\n r = float(input('What is the common ratio'))\n time.sleep(1)\n print('hmm...')\n time.sleep(1)\n print(geom(a, r))\n else:\n print('ok, see you next time')\n\n\n\nif(__name__=='__main__'):\n main()\n","repo_name":"RohanKD/IDT-SMF-2021","sub_path":"SMF_18.py","file_name":"SMF_18.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33340114996","text":"#coding=UTF-8\n__author__ = 'Administrator'\n\nimport datetime\nimport decimal\n\nfrom util.exceptions import *\nfrom util.validators import *\n\n\ndate_fmt_str = 'yyyy-MM-dd'\ndatetime_fmt_str = 'yyyy-MM-dd HH:mm:ss'\nkey_field_value = 'field_value'\nkey_field_type = 'field_type'\n\ndef get_type_value_dic(type, value):\n return {key_field_type:type, key_field_value:value}\n\nclass Field(object):\n\n default_error_msg = {\n 'transfer_to_python': 'The value(%(field_value)) transfer to %(field_type) error '\n }\n def __init__(self,\n name = None,\n comment = None,\n primaryKey = False,\n data = None,\n default = None,\n maxLength = None,\n unique = False,\n blank = True,\n auto = False,\n column = None,\n tablespace = None,\n validators = [],\n error_msg = None\n ):\n self.name = name\n self.comment = comment\n self.primaryKey = primaryKey\n self.data = data\n self.default = default\n self.maxLength = maxLength\n self.unique = unique\n self.blank = blank\n self.auto = auto\n self.column = name or column\n self.tablespace = tablespace\n self.validators = validators\n self.error_msg = error_msg\n\n def to_python(self, value):\n return value\n\n def get_type(self):\n return self.__class__.__name__\n\n def get_name_column(self):\n return (self.name, self.column)\n\n def get_default(self):\n if self.default is not None:\n if callable(self.default):\n return self.default()\n return self.default\n return None\n\n def set_data_from_db(self, data):\n self.data = self.to_python(data)\n\n def get_create_field_sql(self):\n return \"\"\n\n# 布尔类型\nclass BooleanField(Field):\n\n def __init__(self, *args, **kwargs):\n kwargs['blank'] = True\n if 'default' not in kwargs and not kwargs.get('null'):\n kwargs['default'] = False\n Field.__init__(self, *args, **kwargs)\n\n def get_type(self):\n return 'BooleanField'\n\n def to_python(self, value):\n if value in (True, False):\n return bool(value)\n elif value in ('true', 'True', 1):\n return True\n elif value in ('false', 'False', 0):\n return False\n else:\n msg = Field.default_error_msg['transfer_to_python'] % get_type_value_dic(self.get_type(),value)\n raise ValidateError(msg)\n\n def get_create_field_sql(self):\n sql = self.column + \" integer \"\n if self.default is not None and isinstance(self.default, bool):\n sql += \" default \" + int(self.default)\n\n# 字符串类型\nclass CharField(Field):\n \n def __init__(self, *args, **kwargs):\n super(CharField, self).__init__(*args, **kwargs)\n self.validators.append(MaxLengthValidator)\n\n def get_type(self):\n return 'CharField'\n\n def to_python(self, value):\n try:\n if isinstance(value, str) or value is None:\n return value\n else:\n return str(value, \"utf-8\")\n except Exception as e:\n msg = Field.default_error_msg['transfer_to_python'] % get_type_value_dic(self.get_type(),value)\n raise ValidateError(msg)\n\n def get_create_field_sql(self):\n sql = self.column + \" text \"\n if self.default is not None and isinstance(self.default, str):\n sql += \" default \" + str(self.default)\n if not self.blank :\n sql += ' not null '\n if self.unique :\n sql += ' unique '\n return sql\n\n# 日期类型\nclass DateField(Field):\n def __init__(self, auto=False, **kwargs):\n if auto is True:\n self.data = datetime.date()\n super.__init__(self, auto=auto, **kwargs)\n\n def get_type(self):\n return 'DateField'\n\n def to_python(self, value):\n try:\n if isinstance(value, datetime.date) or value is None:\n return value\n elif isinstance(value, datetime.datetime):\n return value.date()\n elif isinstance(value, str):\n return datetime.datetime.strptime(value, date_fmt_str)\n except Exception as e:\n msg = Field.default_error_message['invalid'] % get_type_value_dic(self.get_type(),value)\n raise ValidateError(msg)\n\n def get_create_field_sql(self):\n sql = self.column + \" date \"\n if self.default is not None and isinstance(self.default, datetime.date):\n sql += \" default \" + str(self.default)\n if not self.blank :\n sql += ' not null '\n return sql\n\n#时间类型\nclass DateTimeField(Field):\n def __init__(self, auto=False, **kwargs):\n if auto is True:\n self.data = datetime.datetime()\n super.__init__(self, auto=auto, **kwargs)\n\n def get_type(self):\n return 'DateTimeField'\n\n def to_python(self, value):\n try:\n if isinstance(value, datetime.datetime) or value is None:\n return value\n elif isinstance(value, datetime.date):\n return datetime.datetime(value.year, value.month, value.day)\n elif isinstance(value, str):\n return datetime.datetime.strptime(value, datetime_fmt_str)\n except Exception as e:\n msg = Field.default_error_message['invalid'] % get_type_value_dic(self.get_type(),value)\n raise ValidateError(msg)\n\n def get_create_field_sql(self):\n sql = self.column + \" datetime \"\n if self.default is not None and isinstance(self.default, datetime.datetime):\n sql += \" default \" + str(self.default)\n if not self.blank :\n sql += ' not null '\n return sql\n#整型\nclass IntegerField(Field):\n\n def __init__(self, *args, **kwargs):\n super(IntegerField, self).__init__(*args, **kwargs)\n\n def get_type(self):\n return 'IntegerField'\n\n def to_python(self, value):\n try:\n if isinstance(value, int) or value is None:\n return value\n else:\n return int(value)\n except Exception as e:\n msg = Field.default_error_message['invalid'] % get_type_value_dic(self.get_type(),value)\n raise ValidateError(msg)\n\n def get_create_field_sql(self):\n sql = self.column + \" integer \"\n if self.primaryKey:\n sql += \" primary key \"\n else:\n if self.unique :\n sql += ' unique '\n if not self.blank :\n sql += ' not null '\n if self.default is not None and isinstance(self.default, int):\n sql += \" default \" + int(self.default)\n return sql\n#浮点型\nclass FloatField(Field):\n\n def __init__(self, *args, **kwargs):\n super.__init__(self, *args, **kwargs)\n def get_type(self):\n return 'FloatField'\n\n def to_python(self, value):\n try:\n if isinstance(value, float) or value is None:\n return value\n else:\n return float(value)\n except Exception as e:\n msg = Field.default_error_message['invalid'] % get_type_value_dic(self.get_type(),value)\n raise ValidateError(msg)\n\n def get_create_field_sql(self):\n sql = self.column + \" float \"\n if self.default is not None and isinstance(self.default, float):\n sql += \" default \" + float(self.default)\n if not self.blank :\n sql += ' not null '\n if self.unique :\n sql += ' unique '\n return sql\n\n#decimal类型\nclass DecimalField(Field):\n def __init__(self, p=10,s=0, **kwargs):\n self.p = p\n self.s = s\n super.__init__(self, **kwargs)\n\n def get_type(self):\n return 'DecimalField'\n\n def to_python(self, value):\n try:\n if isinstance(value, decimal.Decimal) or value is None:\n return value\n else:\n return decimal.Decimal(value)\n except Exception as e:\n msg = Field.default_error_message['invalid'] % get_type_value_dic(self.get_type(),value)\n raise ValidateError(msg)\n\n def get_create_field_sql(self):\n sql = self.column + ' decimal(' +self.p+','+self.s+') '\n if self.default is not None and isinstance(self.default, float):\n sql += \" default \" + float(self.default)\n if not self.blank :\n sql += ' not null '\n if self.unique :\n sql += ' unique '\n return sql","repo_name":"zyd915/python-lottery","sub_path":"sports-lottery-v1.0/src/util/db/model/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":8737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"40146019612","text":"\"\"\"\nButynets' Danylo\nPython 3.8\n\"\"\"\n\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nfrom dictionary import Dict\nfrom music_adt import MusicADT\n\n\ndef song_clearer(name):\n \"\"\"\n Return very simplified name of the artist, so that\n Spotipy could find him/her/them and his/her/their track\n with a higher chance.\n :param name: str\n :return: str\n \"\"\"\n if \" x \" in name:\n name = name[:name.index(\" x \")]\n if name == \"The FiNATTiCZ \":\n name = name.replace(\"The \", \"\")\n if \"&\" in name.lower():\n name = name[:name.index(\"&\")]\n if \" feat\" in name.lower():\n name = name[:name.lower().index(\" feat\")]\n if \" and \" in name.lower():\n name = name[:name.lower().index(\" and \")]\n if \"with\" in name.lower():\n name = name[:name.lower().index(\"with\")]\n if \",\" in name.lower():\n name = name[:name.index(\",\")]\n if \"xa0\" in name.lower():\n name = name[:name.index(\"xa0\") - 1]\n if \"/\" in name.lower():\n name = name[:name.index(\"/\")]\n if \"(\" in name.lower():\n name = name[:name.index(\"(\")]\n if \" by \" in name.lower():\n name = name[:name.lower().index(\" by \")]\n return name\n\n\ndef rough_genre_generalization(genres):\n \"\"\"\n (list) -> tuple or str\n Generalize all tracks genres to a single basic one,\n the list of basic genres is determined earlier in the source mentioned\n on the wiki page 0.\n :return: tuple or str\n \"\"\"\n basic = [(\"rap\", \"hip-hop\"), \"pop\", \"country\", \"rock\",\n \"jazz\", \"folk\", \"latin\", \"blues\", \"punk\", \"soul\",\n \"pop standards\", \"r&b\", \"metal\", (\"house\", \"electronic\", \"trance\"),\n (\"ska\", \"reggae\", \"dancehall\"), \"rock-and-roll\", \"swing\"]\n\n count = Dict()\n\n for raw in basic:\n count[raw] = 0\n if isinstance(raw, tuple):\n for subgenre in raw:\n for gen in genres:\n if subgenre in gen:\n count[raw] += 1\n else:\n for gen in genres:\n if raw in gen:\n count[raw] += 1\n res = basic[0]\n for g in basic:\n if count[g] > count[res]:\n res = g\n return res\n\n\ndef raw_year_top(year):\n \"\"\"\n Parse through the the web-page and collect all the data necessary for using\n Spotify API (artists names and their songs). Different years have different HTML markdown.\n :param year: int\n :return: list\n \"\"\"\n # Year 1940 has other address than other years for some reason.\n if year == 1940:\n html = urllib.request.urlopen(f\"http://billboardtop100of.com/336-2/\")\n else:\n html = urllib.request.urlopen(f\"http://billboardtop100of.com/{year}-2/\")\n soup = BeautifulSoup(html, 'html.parser')\n\n yearly_top = []\n if year in [1940, 1943, 1944]:\n for songs in soup.find_all(\"p\"):\n songs = str(songs).replace(\"

\", \"\").replace(\"

\", \"\").replace(\"\\n\", \"\").split(\"
\")\n song_list = songs\n break\n for song in song_list:\n tmp_list = list()\n tmp_list.append(song[:song.index(\".\")])\n tmp_list.append(song[song.index(\"–\") + 2:])\n tmp_list.append(song[song.index(\".\") + 2: song.index(\"–\") - 1])\n yearly_top.append(tmp_list)\n\n elif year == 1942:\n unreachable = [\"41\", \"The Glenn Miller Orchestra\",\n \"(There’ll Be Bluebirds Over) The White Cliffs of Dover\"]\n for song in soup.find_all(\"p\"):\n tmp_list = list()\n for s in song.strings:\n try:\n if int(s[0]):\n tmp_list.append(s[:s.index('.')])\n tmp_list.append(s[s.index(\"by \") + 3:])\n tmp_list.append(s[s.index('.') + 1: s.index(\" by\")])\n yearly_top.append(tmp_list)\n if int(s[:2]) == 40:\n yearly_top.append(unreachable)\n except ValueError:\n continue\n\n elif year == 2013:\n for songs in soup.find_all(\"small\"):\n songs = str(songs).replace(\"\", \"\").replace(\"\", \"\").split(\"
\")\n for song in songs:\n song.replace(\"\\n\", \"\")\n tmp_list = list()\n tmp_list.append(song[:song.index(\".\")].strip())\n line = \"–\" if \"–\" in song else \"-\"\n tmp_list.append((song[song.index(\".\") + 5: song.index(line)]))\n tmp_list.append(song[song.index(line) + 2:])\n yearly_top.append(tmp_list)\n yearly_top[99][2] = \"Beware\"\n\n elif year == 2015:\n tmp_list = list()\n for s in soup.find_all(\"h6\"):\n try:\n s = str(s).replace(\"
\", \"\").replace(\"
\", \"\")\n if s == \"1\":\n raise ValueError\n if int(s) < 101:\n yearly_top.append(tmp_list)\n tmp_list = list()\n tmp_list.append(s)\n else:\n raise ValueError\n except ValueError:\n tmp_list.append(s)\n yearly_top.append(tmp_list)\n\n else:\n for song in soup.find_all('tr'):\n tmp_list = list()\n for string in song.strings:\n if string != \"\\n\":\n tmp_list.append(string)\n yearly_top.append(tmp_list)\n\n return yearly_top\n\n\ndef create_json_data():\n \"\"\"\n This function is used to create results.json, it runs for about 20 minutes and collects\n data from all the web-pages and uses it together with Spotipy to create\n a json file with all the info needed.\n (Info is stored as ADT and transformed into dict for json file)\n :return: None\n \"\"\"\n cid = ''\n secret = ''\n\n ccm = SpotifyClientCredentials(client_id=cid, client_secret=secret)\n sp = spotipy.Spotify(client_credentials_manager=ccm)\n\n adt = MusicADT(1940, 2016)\n\n for year in range(1940, 2017):\n yearly = raw_year_top(year)\n top = adt.main[year - 1940]\n\n for song in yearly:\n final = Dict()\n final[\"Position\"] = song[0]\n final[\"Author\"] = song[1]\n final[\"Track\"] = song[2]\n search_name = song_clearer(song[1])\n track_search_name = search_name + \" \" + song[2]\n\n composer = sp.search(search_name, 1, type=\"artist\")\n track = sp.search(track_search_name, 1, type=\"track\")\n\n try:\n artist_genres = composer[\"artists\"][\"items\"][0][\"genres\"]\n final[\"Original Genres\"] = artist_genres\n final[\"Generalized Genre\"] = rough_genre_generalization(artist_genres)\n except IndexError:\n # Spotify might not contain info about artists genres, as such\n # they would be replaced by None.\n final[\"Original Genres\"] = None\n final[\"Generalized Genre\"] = None\n\n try:\n track_sample = track[\"tracks\"][\"items\"][0][\"preview_url\"]\n final[\"Sample\"] = track_sample\n except IndexError:\n # Spotify might not contain link for the track sample, as such\n # it would be replaced by None.\n final[\"Sample\"] = None\n\n top.add(final)\n\n adt.refactor_for_json()\n","repo_name":"Dranixia/Spotify-Music-Research","sub_path":"modules/json_builder.py","file_name":"json_builder.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70110773719","text":"#-------------------------------------------------------------------------------\r\n# Name: DatabaseSelect\r\n# Purpose:\r\n#\r\n# Author: Gürol Güngör\r\n#\r\n# Created: 18.09.2022\r\n# Copyright: (c) Gürol Güngör 2022\r\n# Licence: GNU - General Public Licence\r\n#-------------------------------------------------------------------------------\r\n\r\n# sqlite kitaplığını kullanma\r\nimport sqlite3\r\n\r\n# Databse nereye ve hangi isimle olusturulacağı tabnımlanır\r\ndatabase = r\"C:\\Database\\rehber.db\"\r\n\r\n# bağlantı oluşturma\r\nconn = sqlite3.connect(database)\r\n\r\n# cursor oluşturma\r\nc = conn.cursor()\r\n\r\n# tablodan sorgulama islemi\r\nc.execute(\"SELECT * FROM rehber\")\r\nprint(c.fetchall())\r\n\r\n# bağlantıyı kapatma\r\nconn.close()","repo_name":"gurolgungor/Python_SQLite","sub_path":"DatabaseSelect.py","file_name":"DatabaseSelect.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17098433005","text":"from django import forms\n\nfrom mainapp.models import Products\nfrom ordersapp.models import Order, OrderItems\n\n\nclass OrderForm(forms.ModelForm):\n class Meta:\n model = Order\n exclude = ('user',) # оставляем пользователя анонимным\n\n def __init__(self, *args, **kwargs):\n super(OrderForm, self).__init__(*args, **kwargs)\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control py-4'\n\n\nclass OrderItemForm(forms.ModelForm):\n price = forms.CharField(label='цена', required=False)\n\n class Meta:\n model = OrderItems\n exclude = () # исключать ничего н надо используем все поля\n\n def __init__(self, *args, **kwargs):\n super(OrderItemForm, self).__init__(*args, **kwargs)\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control py-4'\n\n self.fields['product'].queryset = Products.get_items()\n","repo_name":"Bulgakoff/BaseDjango","sub_path":"geekshop/ordersapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32059785288","text":"class Cell:\n obstacle = False\n occupied = False\n def __init__(self, x, y):\n self.pos = (x, y)\n self.x = x\n self.y = y\n\n\nclass Grid:\n def __init__(self, world):\n self.dynamic_obs = []\n self.width, self.heigth = world[\"map\"][\"dimensions\"]\n self.grid = [[Cell(j,i) for i in range(self.width)] for j in range(self.heigth)]\n if world[\"map\"][\"obstacles\"]:\n for obs in world[\"map\"][\"obstacles\"]:\n self.grid[obs[0]][obs[1]].obstacle = True\n if world[\"map\"][\"dynamic_obstacles\"]:\n for dyn in world[\"map\"][\"dynamic_obstacles\"]:\n self.dynamic_obs += [dyn]\n\n\n\n\n \n","repo_name":"KevinNordenhog/LayeredMAPF","sub_path":"world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"8726354239","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport warnings\nimport pandas as pd\nimport numpy as np\nimport multiprocessing as mp\nimport time\nimport os\nfrom multiprocessing import Value, Lock\nfrom numpy.linalg import LinAlgError\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, median_absolute_error\nfrom datetime import datetime as dt\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nwarnings.filterwarnings('ignore')\n\n'''\n File name: arima.py\n Project: EletrobrasQ\n Python Version: 3.6.0\n'''\n__author__ = \"Tiago S. Buzato & Alex Pessoa\"\n__version__ = \"0.1\"\n__email__ = \"tiago.buzato@climatempo.com.br & alexpessoa@climatempo.com.br\"\n__status__ = \"Development\"\n\n# Tag das Mensagens:\n# [I] -> Informacao\n# [A] -> Aviso/Alerta\n# [E] -> Erro\n\nclass Sarimax():\n def __init__(self, _param_p1, _param_d1, _param_q1, _param_p2, _param_d2, _param_q2, _sector, _listvariables,\n _vtarget, _vexog, _parallel, _rootpath, _logger, _verbose):\n self.p1max = _param_p1\n self.d1max = _param_d1\n self.q1max = _param_q1\n self.p2max = _param_p2\n self.d2max = _param_d2\n self.q2max = _param_q2\n self.corenumber = _parallel\n self.sector = _sector\n self.vtarget = _vtarget\n self.vexog = _vexog\n self.listvariables = _listvariables\n self.logger = _logger\n self.verbose = _verbose\n self.rootpath = _rootpath\n self.file = _rootpath+'/src/Base_Vendas_Total_Jun19.xlsx'\n self.outputgraphic = _rootpath+'/outputs/graphics/'\n #self.outputQ = _rootpath+'/outputs/arimaQ/'\n self.lock = mp.Lock()\n self.counter = Value('i', 0)\n self.manager = mp.Manager()\n self.addlist = self.manager.list()\n\n return\n\n # Run Sarimax with some parameters\n def modeling(self, _model, _lenexog, _dfptestset, _dfptrain, _dfptest, _vtarget, _vexog, _p1, _q1, _d1, _p2, _q2, _d2,\n _begindate, _enddate, _lock, _verbose):\n if _verbose:\n print('[I] Modeling to {p1}, {d1}, {q1}, {p2}, {d2}, {q2}.'.format(p1=_d1, d1=_d1, q1=_q1, p2=_p2, d2=_d2,\n q2=_q2))\n self.logger.info('Modeling to {p1}, {d1}, {q1}, {p2}, {d2}, {q2}.'.format(p1=_d1, d1=_d1, q1=_q1, p2=_p2,\n d2=_d2, q2=_q2))\n preds = _dfptestset.copy().to_frame('y_true').assign(y_pred=np.nan)\n aic, bic = [], []\n\n #print(_p1, _d1, _q1, _p2, _d2, _q2)\n\n preds['y_pred'] = _model.predict(steps=1, exog=_dfptest[_vexog], start=_begindate, end=_enddate)\n validator = 0\n\n for i in range(_lenexog, len(_model.pvalues)):\n if _model.pvalues[i] <= 0.05:\n validator = validator + 1\n\n if validator == (len(_model.pvalues) - _lenexog):\n aic.append(_model.aic)\n bic.append(_model.bic)\n preds.dropna(inplace=True)\n mse = mean_squared_error(preds.y_true, preds.y_pred)\n\n testresults = {}\n testresults = [_p1, _d1, _q1, _p2, _d2, _q2, np.sqrt(mse), preds.y_true.sub(preds.y_pred).std(),\n np.mean(aic),\n np.std(aic), np.mean(bic), np.std(bic)]\n\n _lock.acquire()\n self.addlist.append(testresults)\n _lock.release()\n\n self.counter.value = self.counter.value + 1\n # print(\"############## count made {count} ##########\".format(count=self.counter.value))\n\n def seek_parameters(self, _dfptrain, _dfptest, _vtarget, _vexog, _p1max, _d1max, _q1max, _p2max, _d2max, _q2max,\n _lock, _begindate, _enddate, _verbose):\n if _verbose:\n print('[I] Seek parameters.')\n self.logger.info('Seek parameters.')\n # Created variable\n countmaster = 0\n dfptestset = _dfptrain[_vtarget].squeeze()\n lenexog = len(_vexog)\n procs = []\n browserprocs = mp.Process\n\n for p1 in range(_p1max):\n for d1 in range(_d1max):\n for q1 in range(_q1max):\n for p2 in range(_p2max):\n for d2 in range(_d2max):\n for q2 in range(_q2max):\n\n if p1 == 0 and d1 == 0 and q1 == 0:\n continue\n\n try:\n model = SARIMAX(endog=_dfptrain[_vtarget], exog=_dfptrain[_vexog],\n order=(p1, d1, q1),\n seasonal_order=(p2, d2, q2, 12)).fit(disp=False)\n\n except LinAlgError:\n continue\n\n except ValueError:\n continue\n\n countmaster = countmaster + 1\n\n browserprocs = mp.Process(target=self.modeling, args=(\n model, lenexog, dfptestset, _dfptrain, _dfptest, _vtarget, _vexog, p1, q1, d1, p2,\n q2, d2, _begindate, _enddate, _lock, _verbose))\n procs.append(browserprocs)\n browserprocs.start()\n\n #print(\"number of cores created {n}\".format(n=len(procs)))\n while len(procs) >= self.corenumber:\n for thread in procs:\n if not thread.is_alive():\n procs.remove(thread)\n\n browserprocs.join()\n countstep = 0\n\n print(\"################################ Entrando no while ######################################\")\n\n while True:\n if countmaster == self.counter.value:\n print(\"Numero de processos criados é {n} para {count}\".format(n=countmaster, count=self.counter.value))\n break\n else:\n print(\"Wait more a little time...\")\n time.sleep(3)\n print(\"Numero de processos criados é {n} para {count}\".format(n=countmaster, count=self.counter.value))\n countstep = countstep + 1\n\n if countmaster == self.counter.value:\n print(\"Kill all processes\")\n browserprocs.terminate()\n else:\n print(\"Kill fail\")\n browserprocs.terminate()\n\n return 0\n\n # Def to separate dataframe between train and test\n def df_train_test(self, _dfpdepartment, _listvariables, _verbose):\n if _verbose:\n print('[I] Separate between train and test the dataframe.')\n self.logger.info('Separate between train and test the dataframe.')\n\n # Created variable\n dfptrain = pd.DataFrame()\n dfptest = pd.DataFrame()\n\n # Separated data between train and test\n dfptrain, dfptest = _dfpdepartment[_listvariables], _dfpdepartment[_listvariables] # Partial\n\n # Set datetime as index\n dfptrain = dfptrain.set_index('datetime')\n dfptest = dfptest.set_index('datetime')\n\n return dfptrain, dfptest\n\n # Def to create and treat two dataframes (df of department and exogenous)\n def treat_dfpdata(self, _dfpdata, _sector, _verbose):\n if _verbose:\n print('[I] Treating dataframe.')\n self.logger.info('Treating dataframe.')\n\n # Created variables\n dfpdep = pd.DataFrame()\n dfpexogenous = pd.DataFrame()\n\n # Filter dataframe to the department\n dfpdep = _dfpdata['DEPTO'] == _sector.upper()\n dfpdep = _dfpdata[dfpdep].reset_index()\n\n # Drop Column\n dfpdep = dfpdep.drop(['DEPTO', 'index', 'ANO', 'MES'], axis=1)\n\n # Rename columns\n dfpdep = dfpdep.rename(\n columns={'DATA': 'datetime', 'venda_liquida': 'venda', 'qtd_venda_liquida': 'qt_venda', 'IPCA': 'ipca',\n 'PIB': 'pib', 'Temperatura_Media': 't_media', 'Temperatura_Minima': 't_min',\n 'Dummy_Portateis': 'd_port', 'Dummy_Vestuario': 'd_vest', 'Black_Friday': 'd_bf'})\n\n # Sort by datetime\n dfpdep.sort_values(by=['datetime'])\n\n # Create dataframe of exogenous\n dfpexogenous = dfpdep[-12:]\n dfpexogenous.sort_values(by=['datetime'])\n dfpexogenous = dfpexogenous.set_index('datetime')\n dfpexogenous = dfpexogenous.drop(['venda', 'qt_venda'], axis=1)\n\n # Drop fields with null value\n dfpdep = dfpdep.dropna()\n\n # Set columns types\n dfpdep[['qt_venda', 'd_port', 'd_vest', 'd_bf']] = dfpdep[['qt_venda', 'd_port', 'd_vest', 'd_bf']].astype(\n 'int64',\n copy=False)\n dfpexogenous[['d_port', 'd_vest', 'd_bf']] = dfpexogenous[['d_port', 'd_vest', 'd_bf']].astype('int64',\n copy=False)\n\n # apply log in the variables of venda, pib and ipca for the dfpdep\n for column in dfpdep.columns:\n if (('datetime' != column) and ('d_port' != column) and ('d_vest' != column) and ('d_bf' != column) and (\n 't_media' != column) and ('t_min' != column)):\n dfpdep['log_' + column] = np.log(dfpdep[column])\n\n # apply log in the variables of venda, pib and ipca for the dfplexogenous\n for column in dfpexogenous.columns:\n if (('datetime' != column) and ('d_port' != column) and ('d_vest' != column) and ('d_bf' != column) and (\n 't_media' != column) and ('t_min' != column)):\n dfpexogenous['log_' + column] = np.log(dfpexogenous[column])\n\n return dfpdep, dfpexogenous\n\n # Def to load xlsx file from hdfs system to pandas dataframe\n def load_file(self, _file, _verbose):\n if _verbose:\n print('[I] Load file {file} into pandas dataframe.'.format(file=_file))\n self.logger.info('Load file {file} into pandas dataframe.'.format(file=_file))\n\n # created variable\n opened = False\n\n try:\n dfpdata = pd.read_excel(_file)\n except IOError:\n print('[E] Error {error} to open file {file}.'.format(error=IOError, file=_file))\n self.logger.error('Error {error} to open file {file}.'.format(error=IOError, file=_file))\n return dfpdata, opened\n\n opened = True\n\n return dfpdata, opened\n\n def run(self):\n\n #Load file to pandas dataframe\n dfpdata, opened = self.load_file(self.file, self.verbose)\n\n if opened is not True:\n return\n # Treat and get dataframe of department and exogenous\n dfpdepartment, dfpexogenous = self.treat_dfpdata(dfpdata, self.sector, self.verbose)\n\n # Separate between train and test\n dfptrain, dfptest = self.df_train_test(dfpdepartment, self.listvariables, self.verbose)\n\n # Created variables of begin and end datetime to train model\n begindate = dfptest.index[0].date()\n enddate = dfptest.index[len(dfptest) - 1].date()\n\n # Seek the best parameters to prediction sales\n self.seek_parameters(dfptrain, dfptest, self.vtarget, self.vexog, self.p1max, self.d1max, self.q1max,\n self.p2max, self.d2max, self.q2max, self.lock, begindate, enddate, self.verbose)\n\n return\n","repo_name":"TiagoBuzato/prediction_sales","sub_path":"library/sarimax.py","file_name":"sarimax.py","file_ext":"py","file_size_in_byte":11542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20689940936","text":"import camera_KinematicsClass\nimport path_planning\nimport asyncio ,threading\nimport websockets\nfrom queue import Queue\n#from queue import PriorityQueue\n\ndef StartLoop(loop):\n asyncio.set_event_loop(loop)\n loop.run_forever()\n\ncamera1 = camera_KinematicsClass.Camera_kinematics()\n\nasync def RecvMsg(websocket):\n recvText = await websocket.recv()\n if(recvText[0]=='{'):\n return\n cmd=recvText.split(',',1)[0]\n if(cmd == '10'):\n cameraPos = camera1.RefreshFKAbsolute(recvText[7] + recvText[1:7])\n cameraMsg = [12] + cameraPos + recvText[1:8]\n await websocket.send(cameraMsg)\n elif(cmd == '11'):\n cameraPos = camera1.RefreshFKRelative(recvText[7] + recvText[1:7])\n cameraMsg = [12] + cameraPos + recvText[1:8]\n await websocket.send(cameraMsg)\n elif(int(cmd)>=1 and int(cmd)<=8):\n path_planning.ReceQueue.put(recvText)\n else:\n pass\n\nasync def SendMsg(websocket):\n if(not path_planning.SendQueue.empty()):\n message = path_planning.SendQueue.get() #\"0,0,0,0,0,0,0\"\n message = [str(j) for j in message]\n message =','.join(message)\n print(\"test:\",message)\n await websocket.send(message)\n\nasync def mainLogic(websocket,path):\n while(1):\n await SendMsg(websocket)\n await RecvMsg(websocket)\n \ndef PcWebsocketsServer(ipaddr,port):\n pcServer=websockets.serve(mainLogic,ipaddr,port)\n asyncio.get_event_loop().run_until_complete(pcServer)\n asyncio.get_event_loop().run_forever()\n\nif __name__ == '__main__':\n PcWebsocketsServer(\"127.0.0.1\",8282)","repo_name":"Cosecant233/myUEproject","sub_path":"Server_Client/websockets_server.py","file_name":"websockets_server.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9453684509","text":"import socket #imporing socket because we need socket methods and functions\nimport time #importing time for calculating RTT's\n\n#I used Chat GPT for the basic code generation and then edited the code accordingly where changes were needed.\n\n# Server address and port\nserver_address = ('172.31.0.2', 14000) # Here I gave alice1's IP adress because alice1 is acting as a server in my case\n\n# Number of pings client want to send\nnum_pings = int(input(\"Enter the number of pings you want to send: \"))\n\n# Create a TCP socket\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\n# Initialize variables for statistics as we need min, max and avg RTT.\nmin_rtt = float('inf')\nmax_rtt = 0\ntotal_rtt = 0\npacket_loss_count = 0\n\nfor e in range(4): #adding random for loop to disrupt the flow \n e+=4\n\n# Connect to the server\nclient_socket.connect(server_address)\n\nfor seq_numb in range(1, num_pings + 1):\n while True:\n # Get the current timestamp\n timestamp = time.time()\n\n # Create the ping message\n ping_message = f'ping {seq_numb} {timestamp}' #here we are sending 'ping' as a msg to receive PING in caps\n\n # Send the ping message to the server\n client_socket.send(ping_message.encode()) \n\n try:\n # Set a timeout for receiving the response (1 second as asked in the assgnment) \n client_socket.settimeout(1.0)\n\n # Receive the response from the server\n response = client_socket.recv(1024)\n\n # Calculate the round-trip time (RTT)\n rtt = (time.time() - timestamp) * 1000 # in milliseconds (mult by 1000 because 1sec= 1000ms)\n\n # Update statistics so that we can have the most recent min and max\n total_rtt += rtt # in last we will divide this by total number of pings to get the avg time\n if rtt < min_rtt:\n min_rtt = rtt\n if rtt > max_rtt:\n max_rtt = rtt\n\n # Print the response and RTT\n print(f'Response from server: {response.decode()} | RTT: {rtt:.4f} ms') #RTT upto 4 decimal point\n break # Exit the loop if a response is received\n\n except socket.timeout:\n # Handle packet loss\n print(f'Ping {seq_numb}: Request timed out')\n packet_loss_count += 1\n\n# Calculate packet loss percentage\npacket_loss_percentage = (packet_loss_count / num_pings) * 100\n\n\nfor d in range(4): #adding random for loop to disrupt the flow \n d+=4\n\n# Print statistics\nprint(f'\\nPing statistics:')\nprint(f' Packets sent(no. of pings) = {num_pings}')\n#print(f' Packets loss count = {packet_loss_count}')\nprint(f' Packet loss rate = {packet_loss_percentage:.2f}%')\nif num_pings - packet_loss_count > 0:\n print(f' Minimum RTT = {min_rtt:.4f} ms') #RTT upto 4 decimal point\n print(f' Maximum RTT = {max_rtt:.4f} ms') #RTT upto 4 decimal point\n print(f' Average RTT = {total_rtt / (num_pings - packet_loss_count):.2f} ms')\n\n# Close the socket\nclient_socket.close()\n","repo_name":"Arjitg450/IITH-ACN-CS50060","sub_path":"Assignments/TCP and UDP Pinger/TCP/TCPPingerClient.py","file_name":"TCPPingerClient.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"6358976699","text":"import urllib.request\nimport xml.dom.minidom\nimport urllib.error\nimport xmltodict\n\n\nURL_RAIZ = \"http://www.camara.gov.br/SitCamaraWS/SessoesReunioes.asmx\"\nMETODO_TEOR_DISCURSO = \"/obterInteiroTeorDiscursosPlenario?codSessao=%s&numOrador=%s&numQuarto=%s&numInsercao=%s\"\nMETODO_LISTAR_DISCURSOS = \"/ListarDiscursosPlenario?dataIni=%s&dataFim=%s&codigoSessao=%s\" \\\n \"&parteNomeParlamentar=%s&siglaPartido=%s&siglaUF=%s\"\n\nELEMENTOS_SESSAO_PLENARIO = [\"nome\", \"partido\", \"uf\", \"horaInicioDiscurso\", \"discursoRTFBase64\"]\n\ndef obterInteiroTeorDiscursosPlenario(cod_sessao, num_orador, num_quarto, num_insercao):\n url = URL_RAIZ + METODO_TEOR_DISCURSO % (cod_sessao, num_orador, num_quarto, num_insercao)\n sessao_dict = dict()\n try:\n with urllib.request.urlopen(url) as response:\n html = response.read()\n\n tree = xml.dom.minidom.parseString(html)\n sessao = tree.getElementsByTagName(\"sessao\")[0]\n\n for elemento in ELEMENTOS_SESSAO_PLENARIO:\n valor_elemento = sessao.getElementsByTagName(elemento)[0].firstChild.nodeValue\n sessao_dict[elemento] = valor_elemento.strip()\n\n except urllib.error.HTTPError as http_error:\n if http_error.code == 403:\n raise Exception(\"Bloqueado\")\n raise Exception({\"code\": http_error.code, \"reason\": http_error.reason})\n\n return sessao_dict\n\ndef listarDiscursosPlenario(dataIni, dataFim, codigoSessao=\"\", parteNomeParlamentar=\"\",\n siglaPartido=\"\", siglaUF=\"\"):\n url = URL_RAIZ + METODO_LISTAR_DISCURSOS % (dataIni, dataFim, codigoSessao,\n parteNomeParlamentar, siglaPartido, siglaUF)\n discursos = dict()\n try:\n with urllib.request.urlopen(url) as response:\n xml = response.read()\n discursos = xmltodict.parse(xml)\n\n except urllib.error.HTTPError as http_error:\n if http_error.code == 403:\n raise Exception(\"Bloqueado\")\n raise Exception({\"code\": http_error.code, \"reason\": http_error.reason})\n\n return discursos\n\n\nif __name__ == \"__main__\":\n import json\n print(json.dumps(listarDiscursosPlenario(dataIni='01/06/2016', dataFim='02/06/2016'), indent=4))","repo_name":"BRIGroup-2016/PyCamara","sub_path":"CamaraWS.py","file_name":"CamaraWS.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22936981328","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom math import *\nfrom PyQt5 import QtCore\nimport numpy as np\nimport sys\nimport os\n\n################################################################################\nclass Airfoil(QtCore.QObject):\n ###############################################\n data_changed = QtCore.pyqtSignal()\n\n def __init__(self, filename = None):\n super().__init__()\n self.loaded = False\n self.name = \"\"\n self.r = 0\n self.s = 100\n self.t = [0, 0]\n self.d = 0\n self.lead_in_out = 10\n self.orig_data = self.trans_data = np.array([[],[]])\n if filename is not None :\n self.load(filename)\n ###############################################\n def load_cutting_path(self, filename):\n x = list()\n y = list()\n fp = open(filename)\n line = ' '\n while line != \"\":\n line = fp.readline()\n words = line.split()\n try:\n if len(words) == 2:\n a, b = (float(words[0]), float(words[1]))\n x.append(a)\n y.append(b)\n except ValueError:\n pass\n self.orig_data = np.array([x, y])\n\n # normalize x between 0 and 1\n min_x = self.orig_data[0].min()\n max_x = self.orig_data[0].max()\n self.orig_data[0] -= min_x\n if(max_x == min_x):\n self.loaded = False\n return\n self.orig_data /= (max_x - min_x)\n\n #if(not self.__compute_leading_edge()):\n # self.orig_data = self.trans_data = np.array([[],[]])\n # self.loaded = False\n # return\n\n self.orig_data[0] = -self.orig_data[0]\n self.loaded = True\n self.name = os.path.splitext(os.path.basename(filename))[0]\n self.__apply_transform()\n\n def load(self, filename):\n x = list()\n y = list()\n fp = open(filename)\n line = ' '\n while line != \"\":\n line = fp.readline()\n words = line.split()\n try:\n if len(words) == 2:\n a, b = (float(words[0]), float(words[1]))\n x.append(a)\n y.append(b)\n except ValueError:\n pass\n self.orig_data = np.array([x, y])\n\n # normalize x between 0 and 1\n min_x = self.orig_data[0].min()\n max_x = self.orig_data[0].max()\n self.orig_data[0] -= min_x\n if(max_x == min_x):\n self.loaded = False\n return\n self.orig_data /= (max_x - min_x)\n\n if(not self.__compute_leading_edge()):\n self.orig_data = self.trans_data = np.array([[],[]])\n self.loaded = False\n return\n\n self.orig_data[0] = -self.orig_data[0]\n self.loaded = True\n self.name = os.path.splitext(os.path.basename(filename))[0]\n self.__apply_transform()\n ###############################################\n def __str__(self):\n return str(self.trans_data)\n ###############################################\n def rotate(self, rotation):\n self.r = rotation\n self.__apply_transform()\n ###############################################\n def scale(self, scale):\n self.s = scale\n self.__apply_transform()\n ###############################################\n def translate_x(self, translation_x):\n self.t[0] = translation_x\n self.__apply_transform()\n ###############################################\n def translate_y(self, translation_y):\n self.t[1] = translation_y\n self.__apply_transform()\n ###############################################\n def dilate(self, radius):\n self.d = radius\n self.__apply_transform()\n ###############################################\n def set_lead(self, lead):\n self.lead_in_out = lead\n self.__apply_transform()\n ###############################################\n def __apply_dilate(self, radius):\n x = self.orig_data[0]\n y = self.orig_data[1]\n\n x = np.insert(x, 0, 2*x[0]-x[1])\n y = np.insert(y, 0, 2*y[0]-y[1])\n\n x = np.append(x, 2*x[-1:]-x[-2:-1])\n y = np.append(y, 2*y[-1:]-y[-2:-1])\n\n angle_a = np.arctan2(y[:-1]-y[1:], x[:-1]-x[1:])[:-1] # 1 to end-1\n angle_b = np.arctan2(y[1:]-y[:-1], x[1:]-x[:-1])[1:] # 1 to end-1\n diff = (angle_b - angle_a + 2*pi)%(2*pi)\n\n self.dilate_data = np.stack((\n x[1:-1] - radius * np.cos(angle_a + diff/2),\n y[1:-1] - radius * np.sin(angle_a + diff/2)))\n ###############################################\n def __refresh_transform_mat(self):\n rrad = self.r / 180 * pi\n self.tr_mat = np.array([[self.s*cos(rrad), -self.s*sin(rrad), self.t[0]+self.s],\n [self.s*sin(rrad), self.s*cos(rrad), self.t[1] ],\n [0, 0, 1 ]])\n ###############################################\n def __apply_transform(self):\n if(not self.loaded):\n return\n\n self.__apply_dilate(self.d / self.s)\n self.__refresh_transform_mat()\n\n z_padded = np.pad(self.dilate_data, ((0, 1), (0, 0)), 'constant', constant_values=1)\n self.trans_data = np.dot(self.tr_mat, z_padded)[:-1]\n\n p1 = (self.trans_data[0][0], self.trans_data[1][0])\n p2 = (self.trans_data[0][1], self.trans_data[1][1])\n pm1 = (self.trans_data[0][-1], self.trans_data[1][-1])\n pm2 = (self.trans_data[0][-2], self.trans_data[1][-2])\n\n p1p2_len = sqrt( (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 )\n pm1pm2_len = sqrt( (pm2[0] - pm1[0])**2 + (pm2[1] - pm1[1])**2 )\n\n self.start = (p1[0] - self.lead_in_out * (p2[0] - p1[0]) / p1p2_len, p1[1] - self.lead_in_out * (p2[1] - p1[1]) / p1p2_len)\n self.end = (pm1[0] - self.lead_in_out * (pm2[0] - pm1[0]) / pm1pm2_len, pm1[1] - self.lead_in_out * (pm2[1] - pm1[1]) / pm1pm2_len)\n\n self.data_changed.emit()\n ###############################################\n def get_interpolated_point_list(self, degree_list):\n if(not self.loaded):\n return\n\n it_point_list = np.array([[],[]])\n for degree in degree_list:\n w = self.get_interpolated_point(degree)\n it_point_list = np.append(it_point_list, [[w[0]], [w[1]]], axis=1)\n z_padded = np.pad(it_point_list, ((0, 1), (0, 0)), 'constant', constant_values=1)\n it_point_list = np.dot(self.tr_mat, z_padded)[:-1]\n\n return it_point_list\n ###############################################\n def get_degree_list(self):\n if(not self.loaded):\n return\n\n degree_list = list()\n min_x = self.dilate_data[0][0]\n max_x = self.dilate_data[0][self.leading_edge_idx]\n for i in self.dilate_data[0][:self.leading_edge_idx]:\n degree_list.append((i - min_x) / (max_x - min_x) / 2)\n\n degree_list.append(0.5)\n\n min_x = self.dilate_data[0][-1]\n for i in self.dilate_data[0][self.leading_edge_idx+1:]:\n degree_list.append((1-((i - min_x) / (max_x - min_x))) / 2 + 0.5)\n\n return degree_list\n ###############################################\n def __compute_leading_edge(self):\n edge_candidates = np.where(self.orig_data[0] == 0)[0]\n self.leading_edge_idx = None\n if(len(edge_candidates) == 0):\n print(\"Error : No candidate for leading edge, normalization could have failed.\")\n elif(len(edge_candidates) == 1):\n self.leading_edge_idx = edge_candidates[0]\n elif(len(edge_candidates) == 2):\n if(edge_candidates[0] + 1 != edge_candidates[1]):\n print(\"Error : There exist two leading edge that are not contiguous.\")\n else:\n ys = np.take(self.orig_data[1], edge_candidates)\n middle_y = (ys[0] + ys[1]) / 2\n self.orig_data = np.insert(self.orig_data, edge_candidates[1], [0, middle_y], axis=1)\n self.leading_edge_idx = edge_candidates[1]\n else:\n print(\"Error : More than two leading edge candidates.\")\n\n return self.leading_edge_idx is not None\n ###############################################\n def get_interpolated_point(self, degree):\n if degree <= 0.0 :\n return np.take(self.dilate_data, 0, axis=1)\n\n if degree == 0.5 :\n return np.take(self.dilate_data, self.leading_edge_idx, axis=1)\n\n if degree >= 1.0 :\n return np.take(self.dilate_data, -1, axis=1)\n\n if degree < 0.5 :\n min_x = self.dilate_data[0][0]\n max_x = self.dilate_data[0][self.leading_edge_idx]\n degree_scaled = (max_x - min_x)*degree*2 + min_x\n\n next_idx = np.argmax(self.dilate_data[0] >= degree_scaled)\n prev_idx = next_idx - 1\n\n prev_p = np.take(self.dilate_data, prev_idx, axis=1)\n next_p = np.take(self.dilate_data, next_idx, axis=1)\n\n side_gap = next_p[0] - prev_p[0]\n prev_gap = degree_scaled - prev_p[0]\n return prev_p + ((next_p - prev_p) * prev_gap / side_gap)\n else:\n min_x = self.dilate_data[0][-1]\n max_x = self.dilate_data[0][self.leading_edge_idx]\n degree_scaled = (max_x - min_x)*(1-degree)*2 + min_x\n\n next_idx = np.argmax(self.dilate_data[0][self.leading_edge_idx:] <= degree_scaled) + self.leading_edge_idx\n prev_idx = next_idx - 1\n\n prev_p = np.take(self.dilate_data, prev_idx, axis=1)\n next_p = np.take(self.dilate_data, next_idx, axis=1)\n\n side_gap = prev_p[0] - next_p[0]\n prev_gap = prev_p[0] - degree_scaled\n return prev_p + ((next_p - prev_p) * prev_gap / side_gap)\n################################################################################\n","repo_name":"reederward1285/4AxisFoamCutter","sub_path":"pywing-1.0.0/airfoil.py","file_name":"airfoil.py","file_ext":"py","file_size_in_byte":9959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"32274364070","text":"# 检测输入字符串是否满足需求\ninput_s=input().strip()\n# 检测长度是否在8到32之间\nif not 8<=len(input_s)<=32:\n print(\"不合格\")\n exit()\n\n# 检测首字符是否为大写字符\nif not input_s[0].isupper():\n print(\"不合格\")\n exit()\n\n# 检测是否至少包含一个大写字母、一个小写字母、一个数字、一个特殊符号\n# 大写字母\nupper_flag=False\n# 小写字母\nlower_flag=False\n# 数字\ndigit_flag=False\n# 特殊符号\n# 特殊字符列表\nspecial_list=['!','@','#','$','%','^','&','*','(',')','_','+','-','=','{','}','[',']','|',':',';','\"','<','>','?',',','.','/','~','`']\nspecial_flag=False\nfor char in input_s:\n if char.isupper():\n upper_flag=True\n elif char.islower():\n lower_flag=True\n elif char.isdigit():\n digit_flag=True\n elif char in special_list:\n special_flag=True\nif not upper_flag or not lower_flag or not digit_flag or not special_flag:\n print(\"不合格\")\n exit()\n# 检测是否不包含空格\nif ' ' in input_s:\n print(\"不合格\")\n exit()\nprint(\"合格\")","repo_name":"habunnywy/leetcode","sub_path":"leetcode/科大讯飞第二题.py","file_name":"科大讯飞第二题.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42199971796","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 13 10:32:43 2018\n\n@author: Fotonica\n\"\"\"\n\nfrom .func import file_dialog_save\nfrom .buffer import FIFOBuffer\n\nfrom lantz.qt import QtCore\nfrom lantz.core import ureg\n\nimport numpy as np\n\nimport os\nimport sys\nimport errno\nfrom pathlib import Path\n\nfrom enum import Enum, IntEnum, IntFlag, auto\n\nfrom datetime import datetime\n\n\nclass PATH:\n pass\n\n\nclass DATA:\n pass\n\n\nclass TRIGGER_RETURN:\n def __init__(self, index):\n self.index = index\n\n\nclass INSTANCE_ATTRIBUTE:\n def __init__(self, name):\n self.name = name\n\n\nclass StopConditions(IntFlag):\n COUNT = auto()\n TIME = auto()\n\n\nclass Numerations(IntFlag):\n COUNT = auto()\n TIMESTAMP = auto()\n\n\nclass CallbackModes(IntFlag):\n SERIAL = auto()\n PARALLEL = auto()\n\n\nclass SaveManager(QtCore.QObject):\n \"\"\"\n Clase para implementar guardado de datos automatizado a partir de signals y slots de Qt.\n\n Acepta un signal `trigger` que se emite cada vez que hay una muestra disponible. La muestra se almacena en un buffer\n tipo FIFO hasta llenar un paquete de tamaño configurable, momento en el cual se llama a la función `callback` que\n guarda los datos de cada muestra individualmente.\n\n Parameters\n ----------\n callback : Callable\n Función que guarda los datos de cada muestra. En su firma debe incluir parámetros que acepten la ruta del\n archivo y los datos a guardar de cada muestra (en los argumentos `callback_args` y `callback_kwargs` se\n especifica el orden en el cual se introducen dichos parámetros).\n trigger : PyQt5.signal\n Señal de PyQt5 que indica que una muestra está disponible. En alguno de los returns de cada emisión de la señal\n debe incluirse los datos de la muestra.\n index_of_data : int, opcional\n Índice que indica la posición de los datos de la muestra entre los returns de la emisión del trigger (por\n defecto: 0).\n stop_condition : Union[str, int, StopConditions], opcional\n Criterio de parada determinado por la enumeración StopConditions (por defecto: StopConditions.COUNT, que\n significa la terminación del proceso de guardado una vez que se alcanza un límite de muestras).\n limit : float, opcional\n Valor de límite para determinar el criterio de parada. Si `stop_condition = StopConditions.COUNT`, `limit`\n indica la cantidad de muestras totales a guardar. Si `stop_condition = StopConditions.TIME`, `limit` indica la\n cantidad de tiempo en segundos a registrar (por defecto: 1).\n packet_length : float, opcional\n Las muestras se guardarán de a grupos (paquetes) de tamaño `packet_length`. Este valor se utiliza para definir\n el tamaño del buffer: si `callback_mode = CallbackModes.SERIAL`, el buffer tiene el mismo tamaño que los\n paquetes; si `callback_mode = CallbackModes.PARALLEL`, el tamaño del buffer incluye un determinado overhead dado\n por el valor de `BUFFER_OVERHEAD_IN_PACKETS` (por defecto: 1).\n append : Union[str, int, Numerations], opcional\n Especifica si anexa un sufijo al nombre de archivo (previo a la extensión). Útil para evitar sobrescrituras. Los\n posibles sufijos están determinados por la enumeración Numerations (por defecto: Numerations.TIMESTAMP).\n default_ext: str, opcional\n Extensión del formato de archivos en el cual se guardará la muestra. No está implementado, pero en las clases\n hijas puede servir para completar el nombre de archivo si este no incluye una extensión.\n buffer_init, opcional\n Ejemplo de contenedor de los datos de una única muestra. Permite configurar el buffer como un arreglo de estos\n contenedores. Debe ser compatible con el tipo de datos que devuelve la señal de `trigger` (por defecto: object,\n lo cual significa que puede aceptar cualquier tipo de datos).\n callback_mode : Union[str, int, CallbackModes], opcional\n Establece si el guardado se ejecuta de forma secuencial respecto a la adquisición de datos (lo cual implica una\n pausa en la adquisición de datos) o en paralelo (para una adquisición continua). Actualmente no implementado, lo\n cual significa una escritura en serie.\n\n Arguments\n =========\n\n stop_condition\n stop_flag\n limit\n packet_length\n save_every\n single_file\n buffer\n buffer_init\n path\n append\n default_ext\n index_of_data\n callback_args\n callback_kwargs\n callback_mode\n \"\"\"\n added = QtCore.pyqtSignal(object, object)\n saved = QtCore.pyqtSignal(object, object, object)\n started = QtCore.pyqtSignal()\n stopped = QtCore.pyqtSignal()\n \n stop_condition_set = QtCore.pyqtSignal(object)\n limit_set = QtCore.pyqtSignal(object)\n append_set = QtCore.pyqtSignal(object)\n base_path_set = QtCore.pyqtSignal(object)\n callback_args_set = QtCore.pyqtSignal(object)\n callback_kwargs_set = QtCore.pyqtSignal(object)\n \n BUFFER_OVERHEAD_IN_PACKETS = 5\n \n def __init__(self,\n callback,\n trigger,\n index_of_data=0,\n stop_condition=StopConditions.COUNT,\n limit=1,\n packet_length=1,\n append=Numerations.TIMESTAMP,\n default_ext=\".txt\",\n buffer_init=object,\n single_file=True,\n callback_mode=CallbackModes.SERIAL,\n *args, **kwargs):\n super().__init__()\n\n self._stop_condition = StopConditions.COUNT\n self._limit = 1\n self._packet_length = 1\n self._save_every = 1\n self._single_file = None\n self._buffer_init = None\n self._buffer = FIFOBuffer(init_object=self._buffer_init)\n self._base_path = None\n self._folder = None\n self._base_name = None\n self._extension = None\n self._default_ext = \"\"\n self._append = Numerations(0)\n self._callback_args = ()\n self._callback_kwargs = {}\n self._callback_mode = CallbackModes.SERIAL\n\n self.buffer_init = buffer_init\n \n self.trigger = trigger\n self.index_of_data = index_of_data\n self.callback = callback\n self.callback_args = args\n self.callback_kwargs = kwargs\n \n self.stop_condition = stop_condition\n self.limit = limit\n self.packet_length = packet_length\n self.single_file = single_file\n self.save_every = 1\n self.count = 0\n self.trigger_count = 0\n self.append = append\n self.default_ext = default_ext\n \n self.enabled = False\n self.start_time = None\n self.stop_time = None\n self.run_time = None\n \n @property\n def stop_condition(self):\n return self._stop_condition.value\n \n @stop_condition.setter\n def stop_condition(self, value):\n if isinstance(value, str):\n value = StopConditions[value.upper()]\n elif isinstance(value, int):\n value = StopConditions(value)\n elif isinstance(value, StopConditions):\n pass\n else:\n raise TypeError(\"Value type must be either a StopConditions enum value, a string or an integer.\")\n \n # Change _stop_condition if value differs from previous value\n if value != self._stop_condition:\n self._stop_condition = value\n self.limit = 1\n # Refresh append to avoid lack of numeration and file overwriting\n self.append = self.append\n \n self.stop_condition_set.emit(self.stop_condition)\n \n @property\n def append(self):\n return self._append\n \n @append.setter\n def append(self, value):\n if isinstance(value, type(None)):\n value = Numerations(0)\n elif isinstance(value, bool):\n if value == False:\n value = Numerations(0)\n else:\n raise TypeError(\"Append value must be either a Numerations enum value, a string with a valid numeration name, an integer or a list with any of the above types.\")\n elif isinstance(value, str):\n value = Numerations[value.upper()]\n elif isinstance(value, int):\n value = Numerations(value)\n elif isinstance(value, Numerations):\n pass\n elif isinstance(value, list):\n append = Numerations(0)\n for v in value:\n if isinstance(v, type(None)):\n append |= Numerations(0)\n elif isinstance(v, str):\n append |= Numerations[v.upper()]\n elif isinstance(v, int):\n append |= Numerations(v)\n elif isinstance(v, Numerations):\n append |= v\n else:\n raise TypeError(\"Append value must be either a Numerations enum value, a string with a valid numeration name, an integer or a list with any of the above types.\")\n value = append\n else:\n raise TypeError(\"Append value must be either a Numerations enum value, a string with a valid numeration name, an integer or a list with any of the above types.\")\n \n # To avoid file overwrite, lack of numeration is allowed only for single file operation\n if not value:\n if self._stop_condition == StopConditions.TIME:\n value = Numerations.TIMESTAMP\n if self._stop_condition == StopConditions.COUNT and self.limit > 1:\n value = Numerations.TIMESTAMP\n \n self._append = value\n self.append_set.emit(self._append)\n \n @property\n def path(self):\n name = self._base_name\n \n if self.append & Numerations.TIMESTAMP:\n name += \"_\" + self.get_timestamp()\n if self.append & Numerations.COUNT:\n name += \"_\" + str(self.count)\n\n name += self._extension\n path = Path(self._folder) / name\n \n return str(path)\n \n @path.setter\n def path(self, value):\n if not value:\n self._base_path = None\n self._folder = None\n self._base_name = None\n self._extension = None\n \n self.base_path_set.emit(self._base_path)\n elif not isinstance(value, str):\n raise TypeError(\"File path must be a string with a valid path.\")\n # elif not self.is_pathname_valid(value):\n # raise ValueError(\"Invalid file path\")\n else:\n value = Path(value).resolve()\n\n # if not value.is_file():\n # raise ValueError(\"File path does not point to a file.\")\n \n self._base_path = str(value)\n self._folder = value.parent\n self._base_name = value.stem\n self._extension = value.suffix\n \n if not self._extension:\n self._extension = self._default_ext\n \n self.base_path_set.emit(self._base_path)\n \n def set_path(self, path=None):\n if not path:\n path = self.file_dialog_save()\n \n self.path = path\n \n @property\n def default_ext(self):\n return self._default_ext\n \n @default_ext.setter\n def default_ext(self, value):\n if isinstance(value, type(None)):\n value = \"\"\n elif not isinstance(value, str):\n raise TypeError(\"Default extension must be string type.\")\n \n if value[0] != \".\":\n value = \".\" + value\n \n self._default_ext = value\n \n @property\n def index_of_data(self):\n return self._index_of_data\n \n @index_of_data.setter\n def index_of_data(self, value):\n if not isinstance(value, int):\n raise TypeError(\"Index of data must be int type\")\n \n self._index_of_data = value\n \n @property\n def callback_args(self):\n return self._callback_args\n \n @callback_args.setter\n def callback_args(self, value):\n if not isinstance(value, tuple):\n value = tuple([value])\n self._callback_args = tuple(value)\n \n self.callback_args_set.emit(value)\n \n @property\n def callback_kwargs(self):\n return self._callback_kwargs\n \n @callback_kwargs.setter\n def callback_kwargs(self, value):\n self._callback_kwargs = value\n \n self.callback_kwargs_set.emit(value)\n \n @property\n def callback_mode(self):\n return self._callback_mode\n \n @callback_mode.setter\n def callback_mode(self, value):\n if isinstance(value, CallbackModes):\n pass\n elif isinstance(value, str):\n value = CallbackModes[value]\n elif isinstance(value, int):\n value = CallbackModes(value)\n \n if value == CallbackModes.PARALLEL:\n raise NotImplementedError(\"Parallel callback mode in SaveManager is not yet implemented. Use serial mode instead.\")\n \n self._callback_mode = value\n\n def insert_callback_args(self, data):\n callback_args = list(self.callback_args)\n\n for index, arg in enumerate(callback_args):\n if isinstance(arg, PATH):\n callback_args[index] = self.path\n if isinstance(arg, DATA):\n callback_args[index] = data\n # elif isinstance(arg, TRIGGER_RETURN):\n # callback_args[index] = trigger_returns[arg.index]\n elif isinstance(arg, INSTANCE_ATTRIBUTE):\n callback_args[index] = self.__getattribute__(arg.name)\n\n return tuple(callback_args)\n\n def insert_callback_kwargs(self, data):\n callback_kwargs = dict(self.callback_kwargs)\n\n for index, (key, value) in enumerate(callback_kwargs.items()):\n if isinstance(value, PATH):\n callback_kwargs[key] = self.path\n if isinstance(value, DATA):\n callback_kwargs[key] = data\n # elif isinstance(value, TRIGGER_RETURN):\n # callback_kwargs[key] = trigger_returns[value.index]\n elif isinstance(value, INSTANCE_ATTRIBUTE):\n callback_kwargs[key] = self.__getattribute__(value.name)\n\n return callback_kwargs\n\n @property\n def limit(self):\n return self._limit\n\n @limit.setter\n def limit(self, value):\n if self._stop_condition == StopConditions.COUNT:\n self._limit = int(value) if value >= 0 else 0\n elif self._stop_condition == StopConditions.TIME:\n try:\n self._limit = value.to('s')\n except AttributeError:\n self._limit = float(value) * ureg.s\n\n self.limit_set.emit(self._limit)\n\n @property\n def save_every(self):\n return self._save_every\n\n @save_every.setter\n def save_every(self, value):\n value = int(value)\n value = max(value, 1)\n\n self._save_every = value\n\n @property\n def single_file(self):\n return self._single_file\n\n @single_file.setter\n def single_file(self, value):\n self._single_file = bool(value)\n\n @property\n def packet_length(self):\n return self._packet_length\n \n @packet_length.setter\n def packet_length(self, value):\n if not isinstance(value, int):\n try:\n value = int(value)\n except (ValueError, TypeError):\n raise TypeError(\"Packet length must be int type.\")\n \n self._packet_length = value\n \n # Update buffer lengths\n if self._callback_mode == CallbackModes.SERIAL:\n self._buffer.packet_length = value\n self._buffer.length = value\n self._buffer.init_object = self.buffer_init\n elif self._callback_mode == CallbackModes.PARALLEL:\n self._buffer.packet_length = value\n self._buffer.length = value * self.BUFFER_OVERHEAD_IN_PACKETS\n self._buffer.init_object = self.buffer_init\n\n @property\n def stop_flag(self):\n count_flag = self._stop_condition == StopConditions.COUNT and self.buffer.write_counter >= self.limit\n time_flag = self._stop_condition == StopConditions.TIME and self.run_time >= self.limit\n\n return (count_flag or time_flag)\n\n @property\n def buffer(self):\n return self._buffer\n\n @property\n def buffer_init(self):\n return self._buffer_init\n\n @buffer_init.setter\n def buffer_init(self, value):\n self._buffer_init = value\n self._buffer.init_object = value\n\n def add_to_buffer(self, *trigger_returns):\n self.buffer(trigger_returns[self.index_of_data])\n\n def start(self):\n if not self._base_path:\n self.set_path()\n \n self.count = 0\n self.start_time = datetime.now()\n self.stop_time = None\n self.enabled = True\n \n self.buffer.packet_filled.connect(self.save)\n self.trigger.connect(self.run)\n self.started.emit()\n \n def stop(self):\n self.enabled = False\n self.trigger.disconnect(self.run)\n self.buffer.packet_filled.disconnect(self.save)\n self.stopped.emit()\n \n self.stop_time = datetime.now()\n \n def run(self, *trigger_returns):\n if self.enabled:\n self.trigger_count += 1\n self.update_run_time()\n \n if self.trigger_count % self.save_every == 0:\n self.buffer(trigger_returns[self.index_of_data])\n self.added.emit(self.buffer.write_counter, self.run_time)\n \n # Check for stop condition\n if self.stop_flag:\n self.stop()\n \n # Save remaining data\n remaining_length = self.buffer.write_counter - self.buffer.read_counter\n self.save(remaining_length)\n\n def save(self, data_length=None):\n if isinstance(data_length, type(None)):\n data_length = self._packet_length\n \n if data_length != 0:\n data_array = self.buffer.read(data_length)\n\n if self.single_file and isinstance(data_array, np.ndarray):\n for data in data_array:\n callback_args = self.insert_callback_args(data)\n callback_kwargs = self.insert_callback_kwargs(data)\n self.callback(*callback_args, **callback_kwargs)\n\n self.saved.emit(self.path, self.count, self.run_time)\n self.count += 1\n self.update_run_time()\n else:\n callback_args = self.insert_callback_args(data_array)\n callback_kwargs = self.insert_callback_kwargs(data_array)\n self.callback(*callback_args, **callback_kwargs)\n\n self.saved.emit(self.path, self.count, self.run_time)\n self.count += 1\n self.update_run_time()\n\n self.count = 0\n \n def update_run_time(self):\n if self.start_time:\n self.run_time = (datetime.now() - self.start_time).total_seconds() * ureg.s\n else:\n self.run_time = None\n \n @staticmethod\n def get_timestamp():\n now = datetime.now()\n milis = now.microsecond // 1000\n return now.strftime('%Y%m%d_%H%M%S.') + str(milis)\n \n @staticmethod\n def file_dialog_save(title=\"Guardar archivo\", initial_dir=\"/\", filetypes=[(\"Text files\", \"*.txt\")]):\n \n return file_dialog_save(title=title, initial_dir=initial_dir, filetypes=filetypes)\n \n @staticmethod\n def split_path(path):\n from os.path import split, splitext\n \n folder, full_name = split(path)\n name, extension = splitext(full_name)\n \n return folder, name, extension, full_name\n \n @staticmethod\n def is_pathname_valid(pathname: str) -> bool:\n \"\"\"\n `True` if the passed pathname is a valid pathname for the current OS;\n `False` otherwise.\n \"\"\"\n \n ERROR_INVALID_NAME = 123\n \n # If this pathname is either not a string or is but is empty, this pathname\n # is invalid.\n try:\n if not isinstance(pathname, str) or not pathname:\n return False\n \n # Strip this pathname's Windows-specific drive specifier (e.g., `C:\\`)\n # if any. Since Windows prohibits path components from containing `:`\n # characters, failing to strip this `:`-suffixed prefix would\n # erroneously invalidate all valid absolute Windows pathnames.\n _, pathname = os.path.splitdrive(pathname)\n \n # Directory guaranteed to exist. If the current OS is Windows, this is\n # the drive to which Windows was installed (e.g., the \"%HOMEDRIVE%\"\n # environment variable); else, the typical root directory.\n root_dirname = os.environ.get('HOMEDRIVE', 'C:') \\\n if sys.platform == 'win32' else os.path.sep\n assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law\n \n # Append a path separator to this directory if needed.\n root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep\n \n # Test whether each path component split from this pathname is valid or\n # not, ignoring non-existent and non-readable path components.\n for pathname_part in pathname.split(os.path.sep):\n try:\n os.lstat(root_dirname + pathname_part)\n # If an OS-specific exception is raised, its error code\n # indicates whether this pathname is valid or not. Unless this\n # is the case, this exception implies an ignorable kernel or\n # filesystem complaint (e.g., path not found or inaccessible).\n #\n # Only the following exceptions indicate invalid pathnames:\n #\n # * Instances of the Windows-specific \"WindowsError\" class\n # defining the \"winerror\" attribute whose value is\n # \"ERROR_INVALID_NAME\". Under Windows, \"winerror\" is more\n # fine-grained and hence useful than the generic \"errno\"\n # attribute. When a too-long pathname is passed, for example,\n # \"errno\" is \"ENOENT\" (i.e., no such file or directory) rather\n # than \"ENAMETOOLONG\" (i.e., file name too long).\n # * Instances of the cross-platform \"OSError\" class defining the\n # generic \"errno\" attribute whose value is either:\n # * Under most POSIX-compatible OSes, \"ENAMETOOLONG\".\n # * Under some edge-case OSes (e.g., SunOS, *BSD), \"ERANGE\".\n except OSError as exc:\n if hasattr(exc, 'winerror'):\n if exc.winerror == ERROR_INVALID_NAME:\n return False\n elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:\n return False\n # If a \"TypeError\" exception was raised, it almost certainly has the\n # error message \"embedded NUL character\" indicating an invalid pathname.\n except TypeError:\n return False\n # If no exception was raised, all path components and hence this\n # pathname itself are valid. (Praise be to the curmudgeonly python.)\n else:\n return True\n # If any other exception was raised, this is an unrelated fatal issue\n # (e.g., a bug). Permit this exception to unwind the call stack.\n\n\n\n\n\n\n\n\n","repo_name":"axelmlacap/uc480","sub_path":"uc480/utilities/save.py","file_name":"save.py","file_ext":"py","file_size_in_byte":23785,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"39543069556","text":"#\n# @lc app=leetcode.cn id=19 lang=python3\n#\n# [19] 删除链表的倒数第 N 个结点\n#\n\n# @lc code=start\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 removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n \n if head == None:\n return head\n\n dummy = ListNode(val=-1)\n dummy.next = head\n\n pre_n_pointer = None\n n_pointer = None\n pointer = head\n\n interval_len = 0\n while interval_len != n:\n interval_len += 1\n pointer = pointer.next\n \n pre_n_pointer = dummy\n n_pointer = head\n\n while pointer is not None:\n pre_n_pointer = pre_n_pointer.next\n n_pointer = n_pointer.next\n pointer = pointer.next\n\n pre_n_pointer.next = n_pointer.next\n\n return dummy.next\n\n\n\n\n # if head == None:\n # return head\n\n # dummy = ListNode(val=-1)\n # dummy.next = head\n # pre_current_pointer = dummy\n # current_pointer = head\n\n # # 第一遍 遍历List 获取链表长度\n # len = 0\n # while current_pointer is not None:\n # len += 1\n # current_pointer = current_pointer.next\n\n # # 第二遍 遍历list 删除第 (len-n) 个节点\n # current_pointer = head\n # for i in range(0, len-n):\n # pre_current_pointer = pre_current_pointer.next\n # current_pointer = current_pointer.next\n\n # pre_current_pointer.next = current_pointer.next\n\n # return dummy.next\n\n \n\n# @lc code=end\n\n","repo_name":"MammothKan/LeetCodePlayGround","sub_path":"19.删除链表的倒数第-n-个结点.py","file_name":"19.删除链表的倒数第-n-个结点.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38244423473","text":"import random\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nW,H = 500, 500\nX = np.repeat(np.arange(W).reshape(1, W), H, 0)\nY = np.repeat(np.arange(H).reshape(H, 1), W, 1)\nP = 50, 50\n\n\ndef random_color():\n\treturn random.randrange(255), random.randrange(255), random.randrange(255)\n\ndef random_arr_color(w, h):\n\tc = np.zeros((W, H, 3))\n\n\tc[:,:,0] = random.randrange(255)\n\tc[:,:,1] = random.randrange(255)\n\tc[:,:,2] = random.randrange(255)\n\n\treturn c.astype(np.uint8)\n\n\ndef random_pos(w, h):\n\treturn random.randrange(w), random.randrange(h)\n\n\ndef distance_to_point(p, x, y):\n\treturn np.sqrt((p[0]-x)**2 + (p[1]-y)**2)\n\n\ndef create_color_matrice_V1(m, max_value):\n\ta = (np.repeat(m.reshape((*m.shape, 1)), 3, 2) * (255/max_value))\n\ta[a > 255] = 255\n\treturn (a).astype(np.uint8)\n\ndef create_color_matrice_V2(*matrice):\n\tfinal = np.ones((W, H, 3)).astype(np.uint8)\n\tfor i, dist_arr in enumerate(matrice):\n\t\tc = np.ones((W, H)).astype(bool)\n\t\tcolor = random_color()\n\t\tfor loop in range(len(matrice)-1):\n\t\t\tid = (loop + i + 1) % (len(matrice)-1)\n\n\t\t\tc[dist_arr > matrice[loop]] = False\n\n\t\tfinal[c] = color\n\t\tprint(i)\n\treturn final\n\n\nif __name__ == '__main__':\n\tn = 30\n\tpoints_lst = [random_pos(W, H) for loop in range(n)]\n\tdist_arr_lst = [distance_to_point(p, X, Y) for p in points_lst]\n\t# for point in points_lst:\n\t# \tplt.plot(*point, 'w.')\n\n\tplt.imshow(create_color_matrice_V2(*dist_arr_lst))\n\tplt.show()\n","repo_name":"WIDZpy/NSI","sub_path":"autre projet/entne.py","file_name":"entne.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31068116955","text":"import requests\nimport json\n\nurl = 'http://localhost:8000'\n\n# fetching records\nx = requests.get(url+\"/books\", headers = {\"HTTP_HOST\": \"localhost:8000\"})\nprint(f\"Status code: {x.status_code} \\n\")\nprint(f\"All Books: {x.text} \\n\")\nx = requests.get(url+\"/books/1\")\nprint(f\"First record: {x.json()} \\n\")\n\n# create records\npayload = {\"isbn\":\"4545454\", \"title\":\"Book Three\", \"author\":{\"firstname\":\"Harry\",\"lastname\":\"White\"}}\nr = requests.post(url+\"/books\", data=payload)\nif r.status_code == 200:\n print(\"Record Added \\n\")\n\nx = requests.get(url+\"/books\", headers = {\"HTTP_HOST\": \"localhost:8000\"})\nprint(f\"All Books: {x.text} \\n\")\n\n# remove records\nr = requests.delete(url+\"/books/1\")\nif r.status_code == 200:\n print(\"Record Removed \\n\")\n\n# edit records\npayload = {\"isbn\":\"454555\", \"title\":\"Updated Title\", \"author\":{\"firstname\":\"Sharron\",\"lastname\":\"Smith\"}}\nr = requests.put(url+\"/books/2\", data=payload)","repo_name":"worksofindustry/restapi_golang","sub_path":"request_test.py","file_name":"request_test.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12014825350","text":"# coding=utf-8\n# Функция func принимает на вход целое число n и печатает числа в интервале\n# от n до 0 (шаг -1). Допишите пропущенные участки кода функции.\n\ndef func(n):\n for i in range(n, -1, -1):\n print(i)\n\n# Test\nfunc(5)\n\nfunc(1)\n","repo_name":"ruslanbogun/soft-group","sub_path":"test/2_2.py","file_name":"2_2.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"69867273237","text":"\"\"\"\nMNIST dataset\n=============\n\nContains 60 000 training images, and 10 000 test images.\nImages are of numbers from 0 to 9 (10 classes total).\nDimensions of each image are 28*28.\n\"\"\"\n\nimport os\nimport urllib.request as urllib\nimport gzip\nimport pickle\n\nfrom typing import Tuple\n\nimport numpy as np\n\ndef load_data(path: str = \"mnist\", save: bool = False) -> Tuple:\n \"\"\"\n Downloads and returns mnist data.\n\n Args:\n path (:obj:`str`, optional): path where you want to save downloaded data, defaults to 'mnist'\n save (bool, optional): true if you want to save the data, false otherwise, defualts to False\n\n Returns:\n Tuple: training_images, training_labels, test_images, test_labels\n \n \"\"\"\n PROJECT_ROOT_DIR = \".\"\n DOWNLOAD_ROOT = \"http://yann.lecun.com/exdb/mnist/\"\n FILENAMES = [\n [\"training_images\",\"train-images-idx3-ubyte.gz\"],\n [\"test_images\",\"t10k-images-idx3-ubyte.gz\"],\n [\"training_labels\",\"train-labels-idx1-ubyte.gz\"],\n [\"test_labels\",\"t10k-labels-idx1-ubyte.gz\"]\n ]\n\n data = {}\n\n data_path = os.path.join(PROJECT_ROOT_DIR, path)\n if save:\n os.makedirs(data_path, exist_ok=True)\n\n for filename in FILENAMES:\n url = DOWNLOAD_ROOT + filename[1]\n print(\"Downloading \" + filename[1])\n with urllib.urlopen(url) as response:\n with gzip.GzipFile(fileobj=response) as f:\n if \"labels\" in filename[0]:\n data[filename[0]] = np.frombuffer(f.read(), np.uint8, offset=8)\n else:\n data[filename[0]] = np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1, 28*28)\n\n if save:\n np.savetxt(os.path.join(data_path, filename[0] + '.csv'), data[filename[0]], fmt='%i', delimiter=',')\n \n data[\"training_images\"] = np.reshape(data[\"training_images\"], (data[\"training_images\"].shape[0], 28, 28))\n\n data[\"test_images\"] = np.reshape(data[\"test_images\"], (data[\"test_images\"].shape[0], 28, 28))\n\n return (data[\"training_images\"], data[\"training_labels\"]), (data[\"test_images\"], data[\"test_labels\"])\n\n ","repo_name":"Stoick01/bluebird","sub_path":"bluebird/datasets/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"4225811912","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom sklearn.externals import joblib\n\n\n# region 加载数据\nreviews = pd.read_csv('./data/Reviews_Clean.csv')\nreviews = reviews.dropna() # 进行一次筛选\nclean_texts = reviews.Text\n\nvocabs_to_int = joblib.load('./textSum/vocabs_to_int')\nint_to_vocabs = joblib.load('./textSum/int_to_vocabs')\n# endregion\n\n\n\nbatch_size = 64\n\n## 测试效果\ndef text_to_seq(text):\n '''Prepare the text for the model'''\n return [vocabs_to_int.get(word, vocabs_to_int['']) for word in text.split()]\n\n# Create your own or use one from the dataset\n# input_sentence = 'I have never eaten an apple before, but this red one was nice\n# I think that I Will try a green apple next time'\n# text = text_to_seq(input_sentence)\nrandom = np.random.randint(0, len((clean_texts)))\ninput_sentence = clean_texts[random]\ntext = text_to_seq(input_sentence)\n\ncheckpoint = './best_model.ckpt'\n\nloaded_graph = tf.Graph()\nwith tf.Session(graph=loaded_graph) as sess:\n # Load saved model\n loader = tf.train.import_meta_graph(checkpoint + '.meta')\n loader.restore(sess, checkpoint)\n\n input_data = loaded_graph.get_tensor_by_name('input:0')\n logits = loaded_graph.get_tensor_by_name('predictions:0')\n text_length = loaded_graph.get_tensor_by_name('text_length:0')\n summary_length = loaded_graph.get_tensor_by_name('summary_length:0')\n keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n\n # Multiply by batch_size to match the model's input parameters\n answer_logits = sess.run(logits, {input_data: [text] * batch_size, summary_length: [np.random.randint(5, 8)],\n text_length: [len(text)] * batch_size, keep_prob: 1.0})[0]\n# Remove the padding from the tweet\npad = vocabs_to_int['']\n\nprint('Original Text: ', input_sentence)\nprint('\\nText')\nprint(' Word Ids: {}'.format([i for i in text]))\nprint(' Input words: {}'.format(' '.join([int_to_vocabs[i] for i in text])))\n\nprint('\\nSummary')\nprint(' Word Ids: {}'.format([i for i in answer_logits if i != pad]))\nprint(' Response Words: {}'.format(' '.join([int_to_vocabs[i] for i in answer_logits if i != pad])))\n","repo_name":"KevinYe1014/seq2seq","sub_path":"InferenceTest.py","file_name":"InferenceTest.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"75208967636","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport cv2\n\nfrom core.config import cfg\nfrom utils.bbox import corner2center\n\nfrom rknnlite.api import RKNNLite\n\nclass NnoTracker_RKNNLite(object):\n def __init__(self,Tback_weight, Xback_weight, Head_weight):\n\n self.score_size = (cfg.TRACK.INSTANCE_SIZE - cfg.TRACK.EXEMPLAR_SIZE) // \\\n cfg.POINT.STRIDE + 1 + cfg.TRACK.BASE_SIZE\n hanning = np.hanning(self.score_size)\n window = np.outer(hanning, hanning)\n self.cls_out_channels = 2\n self.window = window.flatten()\n\n self.points = self.generate_points(cfg.POINT.STRIDE, self.score_size)\n\n #--------------------------------------------------------#\n #--------------modify environment------------------------#\n # 1. T init\n self.rknn_Tback = RKNNLite()\n\n # load RKNN model\n print('--> Load RKNN model')\n ret = self.rknn_Tback.load_rknn(Tback_weight)\n if ret != 0:\n print('Load RKNN model failed')\n exit(ret)\n print('done')\n\n # init runtime environment\n print('--> Init runtime environment')\n\n ret = self.rknn_Tback.init_runtime(core_mask=RKNNLite.NPU_CORE_0)\n if ret != 0:\n print('Init runtime environment failed')\n exit(ret)\n print('done')\n\n # 2. X init\n self.rknn_Xback = RKNNLite()\n\n # Load model\n print('--> rknn_Xback: Loading model')\n ret = self.rknn_Xback.load_rknn(Xback_weight)\n if ret != 0:\n print('rknn_Xback: Load model failed!')\n exit(ret)\n print('rknn_Xback:done')\n\n # Init runtime environment\n print('--> Init runtime environment')\n ret = self.rknn_Xback.init_runtime(core_mask=RKNNLite.NPU_CORE_1)\n if ret != 0:\n print('Init runtime environment failed!')\n exit(ret)\n print('done')\n\n # 3. Head init\n self.rknn_Head = RKNNLite()\n\n # Load model\n print('--> rknn_Head: Loading model')\n ret = self.rknn_Head.load_rknn(Head_weight)\n if ret != 0:\n print('rknn_Head: Load model failed!')\n exit(ret)\n print('rknn_Head:done')\n\n # Init runtime environment\n print('--> Init runtime environment')\n ret = self.rknn_Head.init_runtime(core_mask=RKNNLite.NPU_CORE_2)\n if ret != 0:\n print('Init runtime environment failed!')\n exit(ret)\n print('done')\n\n def generate_points(self, stride, size):\n ori = - (size // 2) * stride\n x, y = np.meshgrid([ori + stride * dx for dx in np.arange(0, size)],\n [ori + stride * dy for dy in np.arange(0, size)])\n points = np.zeros((size * size, 2), dtype=np.float32)\n points[:, 0], points[:, 1] = x.astype(np.float32).flatten(), y.astype(np.float32).flatten()\n\n return points\n\n def _convert_bbox(self, delta, point):\n delta = delta.permute(1, 2, 3, 0).contiguous().view(4, -1)\n delta = delta.detach().cpu().numpy()\n\n delta[0, :] = point[:, 0] - delta[0, :] # x1\n delta[1, :] = point[:, 1] - delta[1, :] # y1\n delta[2, :] = point[:, 0] + delta[2, :] # x2\n delta[3, :] = point[:, 1] + delta[3, :] # y2\n delta[0, :], delta[1, :], delta[2, :], delta[3, :] = corner2center(delta)\n return delta\n\n def _convert_score(self, score):\n if self.cls_out_channels == 1:\n score = score.permute(1, 2, 3, 0).contiguous().view(-1)\n score = score.sigmoid().detach().cpu().numpy()\n else:\n score = score.permute(1, 2, 3, 0).contiguous().view(self.cls_out_channels, -1).permute(1, 0)\n score = score.softmax(1).detach()[:, 1].cpu().numpy()\n return score\n\n def _convert_bbox_numpy(self, delta, point):\n # delta = delta.permute(1, 2, 3, 0).contiguous().view(4, -1)\n # delta = delta.detach().cpu().numpy()\n\n delta = delta.transpose((1,2,3,0)).reshape(4, -1)\n\n delta[0, :] = point[:, 0] - delta[0, :] # x1\n delta[1, :] = point[:, 1] - delta[1, :] # y1\n delta[2, :] = point[:, 0] + delta[2, :] # x2\n delta[3, :] = point[:, 1] + delta[3, :] # y2\n delta[0, :], delta[1, :], delta[2, :], delta[3, :] = corner2center(delta)\n return delta\n\n def _convert_score_numpy(self, score):\n def sofmax(logits):\n e_x = np.exp(logits)\n probs = e_x / np.sum(e_x, axis=-1, keepdims=True)\n return probs\n\n # score = score.permute(1, 2, 3, 0).contiguous().view(self.cls_out_channels, -1).permute(1, 0)\n # score = score.softmax(1).detach()[:, 1].cpu().numpy()\n\n score = score.transpose((1,2,3,0)).reshape(self.cls_out_channels, -1).transpose((1,0))\n score = sofmax(score)[:,1]\n\n return score\n\n def _bbox_clip(self, cx, cy, width, height, boundary):\n cx = max(0, min(cx, boundary[1]))\n cy = max(0, min(cy, boundary[0]))\n width = max(10, min(width, boundary[1]))\n height = max(10, min(height, boundary[0]))\n return cx, cy, width, height\n\n def get_subwindow(self, im, pos, model_sz, original_sz, avg_chans):\n \"\"\"\n args:\n im: bgr based image\n pos: center position\n model_sz: exemplar size\n s_z: original size\n avg_chans: channel average\n \"\"\"\n if isinstance(pos, float):\n pos = [pos, pos]\n sz = original_sz\n im_sz = im.shape\n c = (original_sz + 1) / 2\n # context_xmin = round(pos[0] - c) # py2 and py3 round\n context_xmin = np.floor(pos[0] - c + 0.5)\n context_xmax = context_xmin + sz - 1\n # context_ymin = round(pos[1] - c)\n context_ymin = np.floor(pos[1] - c + 0.5)\n context_ymax = context_ymin + sz - 1\n left_pad = int(max(0., -context_xmin))\n top_pad = int(max(0., -context_ymin))\n right_pad = int(max(0., context_xmax - im_sz[1] + 1))\n bottom_pad = int(max(0., context_ymax - im_sz[0] + 1))\n\n context_xmin = context_xmin + left_pad\n context_xmax = context_xmax + left_pad\n context_ymin = context_ymin + top_pad\n context_ymax = context_ymax + top_pad\n\n r, c, k = im.shape\n if any([top_pad, bottom_pad, left_pad, right_pad]):\n size = (r + top_pad + bottom_pad, c + left_pad + right_pad, k)\n te_im = np.zeros(size, np.uint8)\n te_im[top_pad:top_pad + r, left_pad:left_pad + c, :] = im\n if top_pad:\n te_im[0:top_pad, left_pad:left_pad + c, :] = avg_chans\n if bottom_pad:\n te_im[r + top_pad:, left_pad:left_pad + c, :] = avg_chans\n if left_pad:\n te_im[:, 0:left_pad, :] = avg_chans\n if right_pad:\n te_im[:, c + left_pad:, :] = avg_chans\n im_patch = te_im[int(context_ymin):int(context_ymax + 1),\n int(context_xmin):int(context_xmax + 1), :]\n else:\n im_patch = im[int(context_ymin):int(context_ymax + 1),\n int(context_xmin):int(context_xmax + 1), :]\n\n if not np.array_equal(model_sz, original_sz):\n im_patch = cv2.resize(im_patch, (model_sz, model_sz))\n im_patch = im_patch.transpose(2, 0, 1)\n im_patch = im_patch[np.newaxis, :, :, :]\n im_patch = im_patch.astype(np.float32)\n\n return im_patch\n\n def init(self, img, bbox):\n \"\"\"\n args:\n img(np.ndarray): BGR image\n bbox: (x, y, w, h) bbox\n \"\"\"\n self.center_pos = np.array([bbox[0] + (bbox[2] - 1) / 2,\n bbox[1] + (bbox[3] - 1) / 2])\n self.size = np.array([bbox[2], bbox[3]])\n\n # calculate z crop size\n w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n s_z = round(np.sqrt(w_z * h_z))\n\n # calculate channle average\n self.channel_average = np.mean(img, axis=(0, 1))\n\n # get crop\n z_crop = self.get_subwindow(img, self.center_pos,\n cfg.TRACK.EXEMPLAR_SIZE,\n s_z, self.channel_average)\n\n back_T_in = z_crop.transpose((0,2,3,1))\n\n # self.Toutput = self.rknn_Tback.inference(inputs=[z_crop], data_format='nchw')\n self.Toutput = self.rknn_Tback.inference(inputs=[back_T_in])\n\n self.rknn_Tback.release()\n\n def track(self, img):\n \"\"\"\n args:\n img(np.ndarray): BGR image\n return:\n bbox(list):[x, y, width, height]\n \"\"\"\n w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n s_z = np.sqrt(w_z * h_z)\n scale_z = cfg.TRACK.EXEMPLAR_SIZE / s_z\n s_x = s_z * (cfg.TRACK.INSTANCE_SIZE / cfg.TRACK.EXEMPLAR_SIZE)\n x_crop = self.get_subwindow(img, self.center_pos,\n cfg.TRACK.INSTANCE_SIZE,\n round(s_x), self.channel_average)\n\n ## yuce\n back_X_in = x_crop.transpose((0,2,3,1))\n # self.Xoutput = self.rknn_Xback.inference(inputs=[x_crop], data_format='nchw')\n self.Xoutput = self.rknn_Xback.inference(inputs=[back_X_in])\n\n head_T_in = self.Toutput[0].transpose((0,2,3,1))\n head_X_in = self.Xoutput[0].transpose((0,2,3,1))\n\n # outputs = self.rknn_Head.inference(inputs=[self.Toutput[0], self.Xoutput[0]], data_format='nchw')\n outputs = self.rknn_Head.inference(inputs=[head_T_in, head_X_in])\n\n score = self._convert_score_numpy(outputs[0])\n pred_bbox = self._convert_bbox_numpy(outputs[1], self.points)\n\n # score = self._convert_score(outputs['cls'])\n # pred_bbox = self._convert_bbox(outputs['loc'], self.points)\n\n def change(r):\n return np.maximum(r, 1. / r)\n\n def sz(w, h):\n pad = (w + h) * 0.5\n return np.sqrt((w + pad) * (h + pad))\n\n # scale penalty\n s_c = change(sz(pred_bbox[2, :], pred_bbox[3, :]) /\n (sz(self.size[0] * scale_z, self.size[1] * scale_z)))\n\n # aspect ratio penalty\n r_c = change((self.size[0] / self.size[1]) /\n (pred_bbox[2, :] / pred_bbox[3, :]))\n penalty = np.exp(-(r_c * s_c - 1) * cfg.TRACK.PENALTY_K)\n\n # score\n pscore = penalty * score\n\n # window penalty\n pscore = pscore * (1 - cfg.TRACK.WINDOW_INFLUENCE) + \\\n self.window * cfg.TRACK.WINDOW_INFLUENCE\n\n best_idx = np.argmax(pscore)\n\n bbox = pred_bbox[:, best_idx] / scale_z\n\n lr = penalty[best_idx] * score[best_idx] * cfg.TRACK.LR\n\n cx = bbox[0] + self.center_pos[0]\n\n cy = bbox[1] + self.center_pos[1]\n\n # smooth bbox\n width = self.size[0] * (1 - lr) + bbox[2] * lr\n\n height = self.size[1] * (1 - lr) + bbox[3] * lr\n\n # clip boundary\n cx, cy, width, height = self._bbox_clip(cx, cy, width,\n height, img.shape[:2])\n\n # udpate state\n self.center_pos = np.array([cx, cy])\n self.size = np.array([width, height])\n\n bbox = [cx - width / 2,\n cy - height / 2,\n width,\n height]\n\n best_score = score[best_idx]\n return {\n 'bbox': bbox,\n 'best_score': best_score\n }","repo_name":"Try2ChangeX/NanoTrack_RK3588_python","sub_path":"models/rknnlite_rk3588_tracker.py","file_name":"rknnlite_rk3588_tracker.py","file_ext":"py","file_size_in_byte":11749,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"85"} +{"seq_id":"42044123866","text":"\"\"\"\nGiven two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.\n\nThe overall run time complexity should be O(log (m+n)).\n\nThe solution below is O(n) but it got accepted.\nCan be optimised to O(log (m+n))\n\"\"\"\n\ndef findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n a = 0\n b = 0\n merger = []\n while a= max_depth:\n # Maximum depth reached; cannot determine if the tableau is closed\n return False\n\n # Check if the tableau is closed\n if self._is_tableau_closed(node):\n print(f\"Tableau closed at depth {depth} with signed formula {signed_formula}\")\n return True\n\n # Apply tableau rules to the signed formula\n formula = signed_formula.formula\n if isinstance(formula, And) or isinstance(formula, Or):\n new_signed_formulas = self._handle_and_or(signed_formula)\n elif isinstance(formula, Forall) or isinstance(formula, Exists):\n new_signed_formulas = self._handle_quantifiers(node, signed_formula)\n elif isinstance(formula, Necessity) or isinstance(formula, Possibility):\n new_signed_formulas = self._handle_modal_operators(signed_formula)\n elif isinstance(formula, Not):\n new_signed_formulas = self._handle_not(signed_formula)\n else:\n new_signed_formulas = []\n\n # Debug: Print the new signed formulas generated\n print(f\"New signed formulas: {new_signed_formulas}\")\n\n results = [self.tableau_expansion(node.add_child(new_signed_formula), depth + 1, max_depth) for new_signed_formula in new_signed_formulas]\n return any(results)\n\n def _is_tableau_closed(self, node: TableauNode) -> bool:\n signed_formulas = [node.signed_formula] + [ancestor.signed_formula for ancestor in node.get_ancestors()]\n\n print(\"Signed formulas in the current branch:\")\n for sf in signed_formulas:\n print(sf)\n\n for sf1 in signed_formulas:\n for sf2 in signed_formulas:\n if sf1.formula == sf2.formula and sf1.sign != sf2.sign:\n return True\n\n return False\n\n","repo_name":"gnbonney/SymLogos","sub_path":"symlogos/tableau_prover.py","file_name":"tableau_prover.py","file_ext":"py","file_size_in_byte":6312,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"35734659016","text":"import pygame\r\nimport time\r\nimport random\r\n\r\npygame.init()\r\n\r\n#define game colours\r\n\r\n#colour = (red, green , blue)\r\nwhite = (255,255,255)\r\nblack = (0,0,0)\r\nred = (255 , 0 , 0)\r\ngreen = (0, 155, 0)\r\n\r\ndisplay_width = 800\r\ndisplay_height = 800\r\n\r\n#first get a surface\r\ngame_display = pygame.display.set_mode((display_width,display_height))\r\n\r\n#give game a title\r\npygame.display.set_caption('Slither')\r\n\r\n#will update specific area of surface/whole surface if no parameters entered\r\npygame.display.update()\r\n\r\n#block size is thickness of snake\r\nblock_size = 20\r\nfps = 20\r\n\r\ndirection = 'right'\r\n\r\n#get font for texts\r\nsmallfont = pygame.font.SysFont('comicsansms',25)\r\nmediumfont = pygame.font.SysFont('comicsansms',35)\r\nlargefont = pygame.font.SysFont('comicsansms',50)\r\n\r\n#getting snakehead image \r\nimg = pygame.image.load('snakehead.png')\r\nappleimg = pygame.image.load('apple.png')\r\n\r\ndef pause():\r\n paused = True\r\n while paused:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_c:\r\n paused = False\r\n elif event.key == pygame.K_q:\r\n pygame.quit()\r\n quit()\r\n game_display.fill(white)\r\n message_to_screen('Paused ' , black, -100 , size = 'large')\r\n message_to_screen('Press C to continue or Q to quit',\r\n black,\r\n 25)\r\n pygame.display.update()\r\n clock.tick(5)\r\n\r\ndef score(score):\r\n text = smallfont.render('Score : ' + str(score), True , black)\r\n game_display.blit(text, [0,0])\r\n\r\ndef rand_apple_gen():\r\n rand_apple_x = round(random.randrange(0, display_width-block_size))#/10.0)*10.0\r\n rand_apple_y = round(random.randrange(0, display_height-block_size))#/10.0)*10.0\r\n return rand_apple_x , rand_apple_y\r\n\r\n\r\ndef game_intro():\r\n intro = True\r\n \r\n while intro:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_c:\r\n intro = False\r\n if event.key == pygame.K_q:\r\n pygame.quit()\r\n quit()\r\n intro = False\r\n game_display.fill(white)\r\n message_to_screen('Welcome to Slither !',\r\n green,\r\n y_displace = -100,\r\n size = 'large')\r\n message_to_screen('The objective of the game is to eat red apples !',\r\n black,\r\n -30,\r\n size = 'small')\r\n message_to_screen('The more apples you eat, the longer you get !',\r\n black,\r\n 10,\r\n size = 'small')\r\n message_to_screen('If you run into yourself, or the edges, you die !',\r\n black,\r\n 50,\r\n size = 'small')\r\n message_to_screen('Press C to play or Q to quit or P to pause',\r\n black,\r\n 180,\r\n size = 'small')\r\n pygame.display.update()\r\n clock.tick(15)\r\n\r\ndef snake(block_size, snakelist):\r\n #ensuring snakehead is pointing correct direction\r\n if direction == 'right':\r\n head = pygame.transform.rotate(img,270)\r\n if direction == 'left':\r\n head = pygame.transform.rotate(img,90)\r\n if direction == 'up':\r\n head = img\r\n if direction == 'down':\r\n head = pygame.transform.rotate(img,180)\r\n \r\n #put snakehead on screen - x and y coordinate of last tuple in snake list - i.e the first box/start of snake\r\n game_display.blit(head, (snakelist[-1][0], snakelist[-1][1]))\r\n \r\n #we do [:-1] to ensure the snake head is unchanged\r\n for XnY in snakelist[:-1]:\r\n #drawing a rectangle for snake - [coordinate x , coordinate y, width, height]\r\n pygame.draw.rect(game_display, green, [XnY[0],XnY[1],block_size,block_size])\r\n\r\ndef text_objects(text, colour,size):\r\n if size == 'small':\r\n text_surface = smallfont.render(text, True, colour)\r\n elif size == 'medium':\r\n text_surface = mediumfont.render(text, True, colour)\r\n elif size == 'large':\r\n text_surface = largefont.render(text, True, colour)\r\n #return text_surface, text_rect\r\n return text_surface , text_surface.get_rect()\r\n \r\n \r\n#function to put text on the screen, y_displace is displacement from center\r\ndef message_to_screen(msg,colour,y_displace = 0,size = 'small'):\r\n text_surface, text_rect = text_objects(msg, colour,size)\r\n text_rect.center = (display_width/2), (display_height/2) + y_displace\r\n game_display.blit(text_surface, text_rect)\r\n \r\n \r\n \r\n#setting fps\r\nclock = pygame.time.Clock()\r\n\r\n#game loop\r\ndef game_loop():\r\n input(\"ENter yeysys\")\r\n global direction\r\n direction = 'right'\r\n \r\n game_exit = False\r\n game_over = False\r\n\r\n #lead x is top left of snake\r\n lead_x = display_width / 2\r\n lead_y = display_height / 2\r\n \r\n lead_x_change = 10\r\n lead_y_change = 0\r\n \r\n snakelist = []\r\n snakelength = 1\r\n \r\n #you round the number to a multiple of 10 to ensure snake and apple crossover exactly\r\n rand_apple_x, rand_apple_y = rand_apple_gen()\r\n\r\n#event handling loop\r\n while not game_exit:\r\n #loop if game is over - asks user to quit or play again\r\n while game_over == True:\r\n game_display.fill(white)\r\n #display message of game over\r\n message_to_screen('GAME OVER',\r\n red, \r\n y_displace = -50, \r\n size = 'large')\r\n message_to_screen('PRESS C TO PLAY AGAIN OR Q TO QUIT',\r\n black,\r\n y_displace = 50,\r\n size = 'medium')\r\n #show on display\r\n pygame.display.update()\r\n \r\n #perform action depending on user input\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game_exit = True\r\n game_over = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_q:\r\n game_exit = True\r\n game_over = False\r\n if event.key == pygame.K_c:\r\n game_loop()\r\n #an event is basically the game detecting user input eg clicking the arrow keys\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game_exit = True\r\n #when you press a key\r\n if event.type == pygame.KEYDOWN:\r\n #left arrow key\r\n if event.key == pygame.K_LEFT:\r\n lead_x_change =- block_size\r\n lead_y_change = 0\r\n direction = 'left'\r\n #right arrow key\r\n elif event.key == pygame.K_RIGHT:\r\n lead_x_change = block_size\r\n lead_y_change = 0\r\n direction = 'right'\r\n #up\r\n elif event.key == pygame.K_UP:\r\n lead_y_change =- block_size\r\n lead_x_change = 0\r\n direction = 'up'\r\n #down\r\n elif event.key == pygame.K_DOWN:\r\n lead_y_change = block_size\r\n lead_x_change = 0\r\n direction = 'down'\r\n #pause\r\n elif event.key == pygame.K_p:\r\n pause()\r\n #setting boundaries\r\n if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:\r\n game_over = True\r\n\r\n\r\n #when you let go of a key - stop the movement\r\n #if event.type == pygame.KEYUP:\r\n #if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n #lead_x_change = 0\r\n\r\n #i.e when you click left key - x coordinate is -10\r\n lead_x += lead_x_change\r\n lead_y += lead_y_change\r\n \r\n #set display to white\r\n game_display.fill(white)\r\n \r\n apple_thickness = 30\r\n #draw an apple\r\n #pygame.draw.rect(game_display,red, [rand_apple_x,rand_apple_y, apple_thickness, apple_thickness])\r\n game_display.blit(appleimg,(rand_apple_x,rand_apple_y))\r\n\r\n snakehead = []\r\n\r\n snakehead.append(lead_x)\r\n snakehead.append(lead_y)\r\n \r\n snakelist.append(snakehead)\r\n \r\n if len(snakelist) > snakelength:\r\n del snakelist[0]\r\n \r\n #check if snake has hit itself\r\n for eachsegment in snakelist[:-1]:\r\n if eachsegment == snakehead:\r\n game_over = True\r\n \r\n #draw snake\r\n snake(block_size, snakelist)\r\n \r\n #update the score\r\n score(snakelength - 1)\r\n \r\n #do the changes\r\n pygame.display.update()\r\n \r\n #eating the apple\r\n #if lead_x == rand_apple_x and lead_y == rand_apple_y:\r\n \r\n #if lead_x >= rand_apple_x and lead_x <= rand_apple_x + apple_thickness:\r\n #if lead_y >= rand_apple_y and lead_y <= rand_apple_y + apple_thickness:\r\n #generate a new apple\r\n #rand_apple_x = round(random.randrange(0, display_width-block_size))#/10.0)*10.0\r\n #rand_apple_y = round(random.randrange(0, display_height-block_size))#/10.0)*10.0\r\n #make the snake bigger\r\n #snake\r\n #length +=1\r\n \r\n #eating the apple\r\n #first check if snake is within x range of the apple, rand_apple_x corresponds \r\n #to coordinate of top left of apple. add the apple thickness to get top right\r\n #repeat this to find if top right of snake is within paramaeters of apple\r\n if lead_x > rand_apple_x and lead_x < rand_apple_x + apple_thickness or lead_x + block_size > rand_apple_x and lead_x + block_size < rand_apple_x + apple_thickness:\r\n #repeat this for y cross over\r\n if lead_y > rand_apple_y and lead_y < rand_apple_y + apple_thickness or lead_y + block_size > rand_apple_y and lead_y + block_size < rand_apple_y + apple_thickness:\r\n #generate a new apple\r\n rand_apple_x, rand_apple_y = rand_apple_gen()\r\n #make the snake bigger\r\n snakelength +=1\r\n \r\n \r\n \r\n #set frames per second\r\n clock.tick(fps)\r\n\r\n\r\n #exit pygame\r\n pygame.quit()\r\n quit()\r\n\r\n\r\ninput(\"Enter y\") \r\ngame_intro()\r\ngame_loop()","repo_name":"kcarson097/SnakeGame","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":11062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34115905792","text":"\"\"\"\n Write a function that reverses a string. The input string is given as an \n array of characters char[].\n Do not allocate extra space for another array, you must do this by \n modifying the input array in-place with O(1) extra memory.\n You may assume all the characters consist of printable ascii characters.\n \n Example:\n Input: [\"h\",\"e\",\"l\",\"l\",\"o\"]\n Output: [\"o\",\"l\",\"l\",\"e\",\"h\"]\n\"\"\"\n#Difficulty: Easy\n#478 / 478 test cases passed.\n#Runtime: 204 ms\n#Memory Usage: 18 MB\n\n#Runtime: 204 ms, faster than 91.57% of Python3 online submissions for Reverse String.\n#Memory Usage: 18 MB, less than 5.81% of Python3 online submissions for Reverse String.\n\nclass Solution:\n def reverseString(self, s: List[str]) -> None:\n i = 0\n l = len(s) - 1\n while i <= l:\n s[i], s[l] = s[l], s[i]\n i += 1\n l -= 1\n return s\n","repo_name":"YuriSpiridonov/LeetCode","sub_path":"Easy/344.ReverseString.py","file_name":"344.ReverseString.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"85"} +{"seq_id":"24432952200","text":"from __future__ import print_function\nimport math\n\nclass _NumberName(object):\n def __init__(self):\n self.names = []\n self.values = []\n\n def add_name(self, name, value):\n self.names.append(name)\n self.values.append(value)\n\n def add_names(self, **kwargs):\n for k,v in kwargs.items():\n self.add_name(k, v)\n\n def value_name(self, value):\n i = self.values.index(value)\n return self.names[i]\n\n\n_powers_of_10 = _NumberName()\n_powers_of_10.add_names(thousand=3, million=6, billion=9, trillion=12, quadrillion=15, quintillion=18, sextillion=21,\n septillion=24, octillion=27, nonillion=30, decillion=33, undecillion=36, duodecillion=39,\n tredecillion=42, quattuordecillion=45, quindecillion=48, sexdecillion=51, septendecillion=54,\n octodecillion=57, novemdecillion=60, vigintillion=63)\n\n_ordinal_pow_10 = _NumberName()\n# noinspection PyInterpreter\n_ordinal_pow_10.add_names(thousandth=3, millionth=6, billionth=9, trillionth=12, quadrillionth=18, sextillionth=21,\n septillionth=24, octillionth=27, nonillionth=30, decillionth=33, undecillionth=36, duodecillionth=39,\n tredecillionth=42, quattuordecillionth=45, quindecillionth=48, sexdecillionth=51, septendecillionth=54,\n octodecillionth=57, novemdecillionth=60, vigintillionth=63)\n\n_tens_names = _NumberName()\n_tens_names.add_names(twenty=20, thirty=30, forty=40, fifty=50, sixty=60, seventy=70, eighty=80, ninety=90)\n\n_ordinal_tens = _NumberName()\n_ordinal_tens.add_names(twentieth=20, thirtieth=30, fortieth=40, fiftieth=50, sixtieth=60, seventieth=70, eightieth=80,\n ninetieth=90)\n\n_ones_teens = _NumberName()\n_ones_teens.add_names(zero=0, one=1, two=2, three=3, four=4, five=5, six=6, seven=7, eight=8, nine=9, ten=10,\n eleven=11, twelve=12, thirteen=13, fourteen=14, fifteen=15, sixteen=16, seventeen=17,\n eighteen=18, nineteen=19)\n\n_ordinal_ones_teens = _NumberName()\n_ordinal_ones_teens.add_names(zeroth=0, first=1, second=2, third=3, fourth=4, fifth=5, sixth=6, seventh=7, eighth=8,\n ninth=9, tenth=10, eleventh=11, twelfth=12, thirteenth=13, fourteenth=14, fifteenth=15,\n sixteenth=16, seventeenth=17, eighteenth=18, nineteenth=19)\n\ndef _hundreds_str(num, and_sep=False, ordinal=False):\n if not isinstance(num, int):\n raise TypeError(\"num must be an int\")\n elif num < 0 or num > 999:\n raise ValueError(\"num must be between 0 and 999\")\n if not isinstance(ordinal, bool):\n raise TypeError(\"ordinal must be a boolean\")\n\n if ordinal and num % 100 == 0:\n hundred_str = \"hundredth\"\n else:\n hundred_str = \"hundred\"\n\n if ordinal and num % 10 == 0:\n this_tens = _ordinal_tens\n else:\n this_tens = _tens_names\n\n if ordinal:\n this_ones_teens = _ordinal_ones_teens\n else:\n this_ones_teens = _ones_teens\n\n if and_sep:\n sep = \" and \"\n else:\n sep = \" \"\n\n str_out = \"\"\n\n hundreds = int(num/100)\n if hundreds > 0:\n str_out += _ones_teens.value_name(hundreds) + \" \" + hundred_str\n spacer_string = sep\n else:\n spacer_string = \"\"\n\n tens = num % 100\n if tens < 20:\n if hundreds == 0 or tens > 0:\n # Don't add \"zero\" to the end of non-zero numbers ending in zero\n str_out += spacer_string + this_ones_teens.value_name(tens)\n else:\n ones = num % 10\n tens = 10 * int(tens/10)\n str_out += spacer_string + this_tens.value_name(tens)\n if ones != 0:\n str_out += \"-\" + this_ones_teens.value_name(ones)\n\n return str_out\n\ndef _am_i_last(curr_index, n10s):\n \"\"\"\n Determine if the current number is the last non-zero number in the powers of 10 to represent\n :param n10s: the list of values for each three powers of ten in descending order, i.e. billions,\n millions, thousand\n :return: True if the current index is the last non-zero number, False otherwise\n \"\"\"\n for i in range(curr_index+1, len(n10s)):\n if n10s[i] != 0:\n return False\n\n return True\n\ndef _stringify(num, comma_sep=False, and_sep=False, ordinal='no'):\n \"\"\"\n Returns a text representation of the number given, internal method called by the external interfaces.\n :param num: the number to represent, currently only integers permitted (positive or negative)\n :param comma_sep: boolean (default False), whether commas should be included every three powers of ten, i.e.\n \"one thousand one hundred\" or \"one thousand, one hundred\"\n :param and_sep: boolean (default False), whether \"and\" should be included between the hundreds and tens/ones\n of each three powers of 10, i.e. \"three hundred ten\" vs. \"three hundred and ten\", or \"five hundred one\" vs.\n \"five hundred and one\".\n :param ordinal: string (default 'no'), controls whether the number returned is a cardinal number (i.e. \"one\",\n \"two\") or an ordinal number (\"first\", \"second\"). If set to 'last', only the very last number in the string will\n be an ordinal, i.e. \"one hundred ten thousand and eleventh\". If set to 'all', each group of three powers of ten\n will have the final part made an ordinal number, i.e. \"one hundred ten thousandth and eleventh\".\n :return: string, the text representation\n \"\"\"\n ##################\n # Input checking #\n ##################\n if not isinstance(num, int):\n raise TypeError('num must be an int')\n if not isinstance(comma_sep, bool):\n raise TypeError('comma_sep must be a boolean')\n if not isinstance(and_sep, bool):\n raise TypeError('and_sep must be a boolean')\n if not isinstance(ordinal, str):\n raise TypeError('ordinal must be a string')\n\n ordinal = ordinal.lower()\n allowed_ordinal_vals = ('no', 'last', 'all')\n if ordinal not in allowed_ordinal_vals:\n raise ValueError('ordinal must be one of the strings: {}'.format(', '.join(allowed_ordinal_vals)))\n\n if ordinal == 'all':\n this_pow_10 = _ordinal_pow_10\n else:\n this_pow_10 = _powers_of_10\n\n sub_ordinal = False\n\n num_str = \"\"\n if comma_sep:\n sep = \", \"\n else:\n sep = \" \"\n\n # Split up the number into three digit components, i.e. 0-999, 1000-9999, etc.\n if num < 0:\n neg_string = 'negative '\n num = abs(num)\n else:\n neg_string = ''\n\n if num == 0:\n if ordinal:\n _ordinal_ones_teens.value_name(0)\n else:\n return _ones_teens.value_name(0)\n\n p10_max = int(math.log10(num))\n p10s = [x for x in range(0, p10_max+1, 3)]\n p10s.reverse()\n n10s = [int((num % 10**(p + 3))/10**p) for p in p10s]\n for i in range(len(p10s)):\n p = p10s[i]\n n10 = n10s[i]\n if n10 == 0:\n continue\n elif ordinal != 'no' and _am_i_last(i, n10s):\n this_pow_10 = _ordinal_pow_10\n sub_ordinal = True\n\n # Do not add the separator the first time through\n # Also do not put a comma after the thousands if the\n # ones place is not at least 100\n if p != p10s[0]:\n if p == 0 and n10 < 100:\n if and_sep:\n num_str += \" and \"\n else:\n num_str += \" \"\n else:\n num_str += sep\n\n this_str = _hundreds_str(n10, and_sep=and_sep, ordinal=sub_ordinal)\n num_str += this_str\n if p > 0:\n num_str += \" \" + this_pow_10.value_name(p)\n\n return neg_string + num_str\n\n\ndef cardinal_number(num, comma_sep=False, and_sep=False):\n \"\"\"\n Convert an integer into a string representation as an cardinal number (i.e. one, two, etc.)\n :arg num: the number (as an int) to make into a cardinal number string\n :param comma_sep: boolean (default False), whether commas should be included every three powers of ten, i.e.\n \"one thousand one hundred\" or \"one thousand, one hundred\"\n :param and_sep: boolean (default False), whether \"and\" should be included between the hundreds and tens/ones\n of each three powers of 10, i.e. \"three hundred ten\" vs. \"three hundred and ten\", or \"five hundred one\" vs.\n \"five hundred and one\".\n \"\"\"\n return _stringify(num, comma_sep=comma_sep, and_sep=and_sep, ordinal='no')\n\n\ndef ordinal_number(num, comma_sep=False, and_sep=False, all_ordinal=False):\n \"\"\"\n Convert an integer into a string representation as an ordinal number (i.e. first, second, etc.)\n :arg num: the number (as an int) to make into a cardinal number string\n :param comma_sep: boolean (default False), whether commas should be included every three powers of ten, i.e.\n \"one thousand one hundredth\" or \"one thousand, one hundredth\"\n :param and_sep: boolean (default False), whether \"and\" should be included between the hundreds and tens/ones\n of each three powers of 10, i.e. \"three hundred tenth\" vs. \"three hundred and tenth\", or \"five hundred first\" vs.\n \"five hundred and first\".\n :param all_ordinal: boolean (default False), if False, only the very last number in the string will be an\n ordinal, i.e. \"one hundred ten thousand and eleventh\". If True, each group of three powers of ten will have\n the final part made an ordinal number, i.e. \"one hundred ten thousandth and eleventh\".\n \"\"\"\n if all_ordinal:\n ord_arg = 'all'\n else:\n ord_arg = 'last'\n\n return _stringify(num, comma_sep=comma_sep, and_sep=and_sep, ordinal=ord_arg)\n\n\ndef repeat_number(num, comma_sep=False, and_sep=False):\n \"\"\"\n Convert an integer into a string representation as an repeat number (i.e. once, twice, thrice; above 3 it just\n returns \"four times\", \"five times\" etc.\n :arg num: the number (as an int) to make into a cardinal number string\n :param comma_sep: boolean (default False), whether commas should be included every three powers of ten, i.e.\n \"one thousand one hundred times\" or \"one thousand, one hundred times\"\n :param and_sep: boolean (default False), whether \"and\" should be included between the hundreds and tens/ones\n of each three powers of 10, i.e. \"three hundred ten times\" vs. \"three hundred and ten times\", or \"five hundred\n one times\" vs. \"five hundred and one times\".\n \"\"\"\n if num == 1:\n return \"once\"\n elif num == 2:\n return \"twice\"\n elif num == 3:\n return \"thrice\"\n else:\n return _stringify(num, comma_sep=comma_sep, and_sep=and_sep, ordinal=False) + \" times\"","repo_name":"firsttempora/JLLUtils","sub_path":"jllutils/numtostr.py","file_name":"numtostr.py","file_ext":"py","file_size_in_byte":10614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"35088991601","text":"from django.urls import path\nfrom .views import Login, Register, WalletInfo, DepositFunds, VerifyDeposit\n\n\nurlpatterns = [\n path('register/', Register.as_view()),\n path('login/', Login.as_view()),\n path('wallet_info/', WalletInfo.as_view()),\n path('deposit/', DepositFunds.as_view()),\n path('deposit/verify//', VerifyDeposit.as_view()),\n]\n","repo_name":"Ubaydah/django-paystack","sub_path":"wallet/walletApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"74740365077","text":"def searching(arr):\n s = set()\n for a in arr:\n if a in s:\n return a\n else:\n s.add(a)\n\n\ndef sorting(arr):\n brr = sorted(arr)\n for i in xrange(1, len(brr)):\n if brr[i] == brr[i-1]:\n return brr[i]\n\n\ndef gauss(arr):\n # requires that arr contains _all_ natural numbers from one to len(arr)\n n = len(arr)\n return sum(arr) - n * (n - 1) // 2\n","repo_name":"genos/online_problems","sub_path":"prog_praxis/array_dups.py","file_name":"array_dups.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"9965131353","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python3\nfrom __future__ import unicode_literals\n\nimport telegram\nfrom telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters\nfrom telegram.error import TelegramError\nimport logging\n\nimport os\nimport sys\nfrom threading import Thread\nimport shutil\nimport pickle\nimport datetime\nfrom collections import defaultdict\n\nfrom functools import wraps\n\nwith open(\"api_key.txt\", 'r') as f:\n TOKEN = f.read().rstrip()\n\n# Format is mmddyyyy and then additional letters if I need a hotfix.\nPATCHNUMBER = \"04262020\"\n\nADMIN = [539621524]\n\n\"\"\"\nContains:\n\namas - Key is telegram_id, value is list of (telegram_id, question) tuples.\nusers - A list of (telegram_id, name) tuples.\npatches - A list of strings representing the patch history.\nreply_history - A list of replies in (asker_id, question_text, person_who_made_ama_id, text) tuples.\n\"\"\"\nama_database = pickle.load(open(\"./amadatabase\", \"rb\")) if os.path.isfile(\"./amadatabase\") else {}\n\ndef send_message(bot, chat_id, text, photo=None):\n try:\n bot.send_message(chat_id=chat_id, text=text, parse_mode=telegram.ParseMode.HTML)\n if photo is not None:\n bot.send_photo(chat_id=chat_id, photo=photo, parse_mode=telegram.ParseMode.HTML)\n except TelegramError as e:\n raise e\n\n\ndef static_handler(command):\n text = open(\"static_responses/{}.txt\".format(command), \"r\").read()\n return CommandHandler(command,\n lambda bot, update: send_message(bot, update.message.chat.id, text))\n\n\ndef restricted(func):\n @wraps(func)\n def wrapped(update, context, *args, **kwargs):\n user_id = update.effective_user.id\n if user_id not in ADMIN:\n print(\"Unauthorized access denied for {}.\".format(user_id))\n return\n return func(update, context, *args, **kwargs)\n return wrapped\n\n\ndef send_patchnotes(bot):\n path = \"./static_responses/patchnotes_\" + PATCHNUMBER + \".txt\"\n\n if PATCHNUMBER in ama_database[\"patches\"] or not os.path.isfile(path):\n return\n\n text = open(path, \"r\").read()\n\n for (telegram_id, name) in ama_database[\"users\"]:\n send_message(bot, telegram_id, text)\n\n ama_database[\"patches\"].append(PATCHNUMBER)\n\n\ndef get_username(user):\n username = \"\"\n if user.username is not None:\n username = user.username\n if user.first_name is not None:\n username += \" (\" + user.first_name\n if user.last_name is not None:\n username += \" \" + user.last_name + \")\"\n else:\n username += \")\"\n else:\n if user.first_name is not None:\n username += user.first_name\n if user.last_name is not None:\n username += \" \" + user.last_name\n return username\n\n\ndef confirm_ama_handler(bot, update, user_data):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n if user_data.get(\"current_ama_id_and_text\") is None:\n send_message(bot, chat_id, \"No pending confirmation found!\")\n return\n\n user_id, text = user_data[\"current_ama_id_and_text\"]\n\n if user_id < 0 or user_id >= len(ama_database[\"users\"]):\n send_message(bot, chat_id, \"That (%s) is not a valid ID in the range [%s, %s)!\" %\n (user_id, 0, len(ama_database[\"users\"])))\n return\n\n telegram_id = ama_database[\"users\"][user_id][0]\n\n if telegram_id == user.id:\n send_message(bot, chat_id, \"You can't ask yourself a question!\")\n return\n\n ama_database[\"amas\"][telegram_id].append((user.id, text))\n\n new_question_id = len(ama_database[\"amas\"][telegram_id]) - 1\n send_message(bot, chat_id, \"Your question has been asked!\")\n send_message(bot, telegram_id, \"You have a new question (%s): %s\" % (new_question_id, text))\n send_message(bot, telegram_id, \"You can reply to the sender with /reply %s {text}.\" % new_question_id)\n\n user_data[\"current_ama_id_and_text\"] = None\n\n\ndef ama_handler(bot, update, user_data, args):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n if len(args) < 2:\n send_message(bot, chat_id, \"Usage: /ama {ID from /users or name} {text}\")\n return\n\n text = \" \".join(args[1:])\n\n try:\n user_id = int(args[0])\n except ValueError:\n user_id = -1\n name = str(args[0])\n official_name = \"\"\n for i, tup in enumerate(ama_database[\"users\"]):\n if name.lower() in tup[1].lower():\n user_id = i\n official_name = tup[1]\n break\n if user_id == -1:\n send_message(bot, chat_id, \"Error: Could not find a matching name!\")\n return\n if user_id != -1:\n user_data[\"current_ama_id_and_text\"] = (user_id, text)\n send_message(bot, chat_id, \"Are you sure you want to ask %s this question? If so, use /confirmama.\" % official_name)\n return\n\n if user_id < 0 or user_id >= len(ama_database[\"users\"]):\n send_message(bot, chat_id, \"That (%s) is not a valid ID in the range [%s, %s)!\" %\n (user_id, 0, len(ama_database[\"users\"])))\n return\n\n telegram_id = ama_database[\"users\"][user_id][0]\n\n if telegram_id == user.id:\n send_message(bot, chat_id, \"You can't ask yourself a question!\")\n return\n\n ama_database[\"amas\"][telegram_id].append((user.id, text))\n\n new_question_id = len(ama_database[\"amas\"][telegram_id]) - 1\n send_message(bot, chat_id, \"Your question has been asked!\")\n send_message(bot, telegram_id, \"You have a new question (%s): %s\\n\\n\"\n \"You can reply to the sender with /reply %s {text}.\" %\n (new_question_id, text, new_question_id))\n\n\ndef users_handler(bot, update):\n chat_id = update.message.chat.id\n\n text = \"Users:\\n\\n\"\n for i, tup in enumerate(ama_database[\"users\"]):\n text += \"(%s): %s\\n\" % (i, tup[1])\n send_message(bot, chat_id, text)\n\n\ndef display_handler(bot, update, args):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n if len(args) < 1:\n username = \"\"\n for (id, name) in ama_database[\"users\"]:\n if id == user.id:\n username = name\n break\n\n if username == \"\":\n send_message(bot, chat_id, \"You haven't made an AMA by joining using /am!\")\n return\n\n text = \"AMA for %s:\\n\\n\" % username\n count = 0\n for telegram_id, question in ama_database[\"amas\"][user.id]:\n text += \"(%s) %s\\n\\n\" % (count, question)\n count += 1\n send_message(bot, chat_id, text)\n return\n\n if len(args) > 1:\n send_message(bot, chat_id, \"Usage: /display {ID from /users or name}\")\n return\n\n try:\n user_id = int(args[0])\n except ValueError:\n user_id = -1\n name = \" \".join(args)\n for i, tup in enumerate(ama_database[\"users\"]):\n if name.lower() in tup[1].lower():\n user_id = i\n break\n if user_id == -1:\n send_message(bot, chat_id, \"Error: Could not find a matching name!\")\n return\n\n if user_id < 0 or user_id >= len(ama_database[\"users\"]):\n send_message(bot, chat_id, \"That (%s) is not a valid ID in the range [%s, %s)!\" %\n (user_id, 0, len(ama_database[\"users\"])))\n return\n\n text = \"AMA for %s:\\n\\n\" % ama_database[\"users\"][user_id][1]\n count = 0\n for telegram_id, question in ama_database[\"amas\"][ama_database[\"users\"][user_id][0]]:\n text += \"(%s) %s\\n\\n\" % (count, question)\n count += 1\n send_message(bot, chat_id, text)\n\n\ndef add_me_handler(bot, update, args):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n if len(args) == 0:\n username = get_username(user)\n else:\n username = \" \".join(args)\n\n for id, name in ama_database[\"users\"]:\n if id == user.id:\n send_message(bot, chat_id, \"You're already in the database!\")\n return\n\n ama_database[\"users\"].append((user.id, username))\n # Sort by name\n ama_database[\"users\"] = sorted(ama_database[\"users\"], key=lambda x: str(x[1]).lower())\n\n send_message(bot, chat_id, \"You've been added! Make sure to DM the bot with /start to be able to get messages!\")\n\n\ndef remove_me_confirmed_handler(bot, update):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n for id, name in ama_database[\"users\"]:\n if id == user.id:\n ama_database[\"users\"].remove((id, name))\n break\n\n for id in ama_database[\"amas\"].keys():\n if id == user.id:\n del ama_database[\"amas\"][user.id]\n break\n\n send_message(bot, chat_id, \"You've been removed!\")\n\n\ndef remove_me_handler(bot, update):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n if user.id not in [t[0] for t in ama_database[\"users\"]]:\n send_message(bot, chat_id, \"You haven't made an AMA by joining using /am!\")\n return\n\n send_message(bot, chat_id, \"Are you sure you want to leave? If so, use /rmc.\")\n\n\ndef reply_handler(bot, update, args):\n chat_id = update.effective_chat.id\n user = update.effective_message.from_user\n\n try:\n photo = update.effective_message.photo[-1]\n except Exception as e:\n photo = None\n\n if user.id not in [t[0] for t in ama_database[\"users\"]]:\n send_message(bot, chat_id, \"You haven't made an AMA by joining using /am!\")\n return\n\n if len(args) < 2:\n send_message(bot, chat_id, \"Usage: /reply {question ID} {text}\")\n return\n\n text = \" \".join(args[1:])\n\n try:\n question_id = int(args[0])\n except ValueError:\n send_message(bot, chat_id, \"That (%s) was not a valid question ID.\" % args[0])\n return\n\n if question_id < 0 or question_id >= len(ama_database[\"amas\"][user.id]):\n send_message(bot, chat_id, \"That (%s) is not a valid question ID in the range [%s, %s)!\" %\n (question_id, 0, len(ama_database[\"amas\"][user.id])))\n return\n\n telegram_id, question_text = ama_database[\"amas\"][user.id][question_id]\n\n username = \"\"\n for id, name in ama_database[\"users\"]:\n if user.id == id:\n username = name\n break\n\n ama_database[\"reply_history\"].append((telegram_id, ama_database[\"amas\"][user.id][question_id][1], user.id, text))\n\n send_message(bot, chat_id, \"%s just replied to the question (%s): %s\" % (username, question_id, question_text))\n send_message(bot, telegram_id, \"You asked the following question on the AMA for %s: \"\n \"%s\\n\\nHere is their reply: %s\" % (username, question_text, text), photo=photo)\n send_message(bot, user.id, \"Your reply has been sent!\")\n\n\ndef clear_handler(bot, update, args):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n if user.id not in [t[0] for t in ama_database[\"users\"]]:\n send_message(bot, chat_id, \"You haven't made an AMA by joining using /am!\")\n return\n\n if len(args) == 0:\n ama_database[\"amas\"][user.id] = []\n send_message(bot, chat_id, \"Your AMA has been cleared!\")\n return\n\n try:\n question_id = int(args[0])\n except ValueError:\n send_message(bot, chat_id, \"That (%s) was not a valid question ID.\" % args[0])\n return\n\n if question_id < 0 or question_id >= len(ama_database[\"amas\"][user.id]):\n send_message(bot, chat_id, \"That (%s) is not a valid question ID in the range [%s, %s)!\" %\n (question_id, 0, len(ama_database[\"amas\"][user.id])))\n return\n\n ama_database[\"amas\"][user.id] = ama_database[\"amas\"][user.id][:question_id] + ama_database[\"amas\"][user.id][question_id + 1:]\n send_message(bot, chat_id, \"Question (%s) has been removed from your AMA!\" % question_id)\n\n\ndef mass_ama_handler(bot, update, args):\n chat_id = update.message.chat.id\n user = update.message.from_user\n\n if len(args) < 1:\n send_message(bot, chat_id, \"Usage: /massama {text}\")\n return\n\n text = \" \".join(args)\n\n for id, name in ama_database[\"users\"]:\n if id != user.id:\n ama_database[\"amas\"][id].append((user.id, text))\n\n new_question_id = len(ama_database[\"amas\"][id]) - 1\n send_message(bot, id, \"You have a new question (%s): %s\\n\\n\"\n \"You can reply to the sender with /reply %s {text}.\" %\n (new_question_id, text, new_question_id))\n send_message(bot, chat_id, \"Your question has been asked!\")\n\n\ndef feedback_handler(bot, update, args):\n user = update.message.from_user\n\n username = \"\"\n for id, name in ama_database[\"users\"]:\n if id == user.id:\n username = name\n break\n\n if args and len(args) > 0:\n feedback = open(\"feedback.txt\", \"a+\")\n\n feedback.write(str(update.message.from_user.id) +\n \" (\" + username + \") at \" +\n str(datetime.datetime.now()) + \"\\n\")\n feedback.write(\" \".join(args) + \"\\n\\n\")\n\n feedback.close()\n\n send_message(bot, update.message.chat_id, text=\"Your response has been recorded!\")\n else:\n send_message(bot, update.message.chat_id, text=\"Error: You must input a non-empty string.\")\n\n\ndef save_database(bot, update):\n if os.path.exists(\"amadatabase\"):\n shutil.copy(\"amadatabase\", \"amadatabasebackup\")\n pickle.dump(ama_database, open(\"amadatabase\", \"wb\"))\n\n\ndef handle_error(bot, update, error):\n try:\n raise error\n except TelegramError:\n logging.getLogger(__name__).warning('Telegram Error! %s caused by this update: %s', error, update)\n\n\nif __name__ == \"__main__\":\n bot = telegram.Bot(token=TOKEN)\n updater = Updater(token=TOKEN)\n dispatcher = updater.dispatcher\n\n # Init setup\n\n if ama_database.get(\"amas\") is None:\n ama_database[\"amas\"] = defaultdict(list)\n\n if ama_database.get(\"users\") is None:\n ama_database[\"users\"] = []\n\n if ama_database.get(\"patches\") is None:\n ama_database[\"patches\"] = []\n\n if ama_database.get(\"reply_history\") is None:\n ama_database[\"reply_history\"] = []\n\n # Static commands\n\n static_commands = [\"start\", \"help\"]\n for c in static_commands:\n dispatcher.add_handler(static_handler(c))\n\n # Main commands\n\n ama_aliases = [\"ama\", \"ask\"]\n reply_aliases = [\"reply\", \"r\"]\n display_aliases = [\"display\", \"view\", \"d\"]\n users_aliases = [\"users\", \"u\"]\n add_me_aliases = [\"addme\", \"setname\", \"am\", \"sn\"]\n remove_me_aliases = [\"removeme\", \"rm\"]\n feedback_aliases = [\"feedback\", \"report\"]\n clear_aliases = [\"clear\"]\n mass_ama_aliases = [\"massama\", \"massask\", \"ma\"]\n\n commands = [(\"ama\", 4, ama_aliases),\n (\"reply\", 1, reply_aliases),\n (\"display\", 1, display_aliases),\n (\"users\", 0, users_aliases),\n (\"add_me\", 1, add_me_aliases),\n (\"remove_me\", 0, remove_me_aliases),\n (\"remove_me_confirmed\", 0, [\"rmc\"]),\n (\"feedback\", 1, feedback_aliases),\n (\"confirm_ama\", 3, [\"confirmama\"]),\n (\"clear\", 1, clear_aliases),\n (\"mass_ama\", 1, mass_ama_aliases)]\n\n for c in commands:\n func = locals()[c[0] + \"_handler\"]\n if c[1] == 0:\n dispatcher.add_handler(CommandHandler(c[2], func))\n elif c[1] == 1:\n dispatcher.add_handler(CommandHandler(c[2], func, pass_args=True))\n elif c[1] == 2:\n dispatcher.add_handler(CommandHandler(c[2], func, pass_chat_data=True))\n elif c[1] == 3:\n dispatcher.add_handler(CommandHandler(c[2], func, pass_user_data=True))\n elif c[1] == 4:\n dispatcher.add_handler(CommandHandler(c[2], func, pass_user_data=True, pass_args=True))\n\n # Set up job queue for repeating automatic tasks.\n\n jobs = updater.job_queue\n\n save_database_job = jobs.run_repeating(save_database, interval=3600, first=0)\n save_database_job.enabled = True\n\n # Error handler\n\n dispatcher.add_error_handler(handle_error)\n\n # Logger\n\n logging.basicConfig(\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO, filename='logging.txt', filemode='a+')\n\n # Restart\n\n def stop_and_restart():\n updater.stop()\n os.execl(sys.executable, sys.executable, *sys.argv)\n\n def restart(bot, update):\n save_database(bot, update)\n update.message.reply_text('Bot is restarting...')\n Thread(target=stop_and_restart).start()\n\n dispatcher.add_handler(CommandHandler(\"restart\",\n restart,\n filters=Filters.user(username='@thweaver')))\n\n # Run the bot\n\n send_patchnotes(bot)\n\n updater.start_polling()\n updater.idle()\n","repo_name":"Thought-Weaver/AMA-Telegram-Bot","sub_path":"telegram_bot.py","file_name":"telegram_bot.py","file_ext":"py","file_size_in_byte":16976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41448799890","text":"#\n# File:\n# TRANS_contour_fill.py\n#\n# Synopsis:\n# Illustrates how to create a contour fill plot\n#\n# Categories:\n# contour plot\n#\n# Author:\n# Karin Meier-Fleischer, based on NCL example\n# \n# Date of initial publication:\n# September 2018\n#\n# Description:\n# This example shows how to create a contour fill plot.\n#\n# Effects illustrated:\n# o Drawing a contour fill plot\n# \n# Output:\n# A single visualization is produced.\n#\n# Notes: The data for this example can be downloaded from \n# http://www.ncl.ucar.edu/Document/Manuals/NCL_User_Guide/Data/\n# \n'''\n Transition Guide Python Example: \tTRANS_contour_fill.py\n\n - contour fill plot\n\n 18-09-03 kmf\n'''\nfrom __future__ import print_function\nimport numpy as np\nimport Ngl\n\n#-- create some dummy data to contour\nT = np.zeros((25,25),'f')\njspn = np.power(np.arange(-12,13),2)\nispn = np.power(np.arange(-12,13),2)\n\nfor i in range(0,len(ispn)):\n\tT[i,:] = (jspn + ispn[i]).astype('f')\n\nT = 100.0 - np.sqrt(64 * T)\n\n#-- start the graphics\nwks = Ngl.open_wks(\"png\",\"plot_TRANS_contour_fill_py\")\n\n#-- resource settings\nres = Ngl.Resources()\nres.nglDraw = False #-- don't draw plot\nres.nglFrame = False #-- don't advance the frame\nres.nglPointTickmarksOutward = True #-- point tickmarks outward\n\nres.cnFillOn = True #-- turn on contour level fill\nres.cnLineLabelsOn = False #-- turn off contour line labels\nres.cnFillPalette = \"ncl_default\"\n\nres.lbLabelPosition = \"Center\"\nres.lbLabelFontHeightF = 0.018 #-- make labelbar labels smaller\nres.lbLabelAlignment = \"BoxCenters\"\nres.lbLabelStrings = list(range(-30,110,10)) #-- doesn't appear to work\n\n#-- create the contour plot\nplot = Ngl.contour(wks,T,res)\n\n#-- bug work-around (v1.5.2): apply the labels after the plot has been created\nnrlist = Ngl.Resources()\nnrlist.lbLabelStrings = list(range(-30,110,10))\nNgl.set_values(plot,nrlist)\n\n#-- draw the plot and advance the frame\nNgl.draw(plot)\nNgl.frame(wks)\n\nNgl.end()\n","repo_name":"KMFleischer/PyEarthScience","sub_path":"Transition_examples_NCL_to_PyNGL/contours/TRANS_contour_fill.py","file_name":"TRANS_contour_fill.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"85"} +{"seq_id":"27572768446","text":"class Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n if(head is None or head.next is None):\n return None\n fast, slow = head, head\n while(fast is not None and fast.next is not None):\n fast = fast.next.next\n slow = slow.next\n if(slow == fast):\n break\n if(fast != slow):\n return None\n while(slow != head):\n slow = slow.next\n head = head.next\n return head","repo_name":"KaiChen1998/My-Leetcode","sub_path":"python/142. Linked List Cycle II.py","file_name":"142. Linked List Cycle II.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"26924836222","text":"pet_0 = {\n\t'name': 'agata',\n\t'animal': 'cat',\n\t'owner': 'mari',\n}\n\npet_1 = {\n\t'name': 'mingau',\n\t'animal': 'cat',\n\t'owner': 'lucas',\n}\n\npet_2 = {\n\t'name': 'quica',\n\t'animal': 'dog',\n\t'owner': 'cris',\n}\n\npets = [pet_0, pet_1, pet_2]\nfor pet in pets:\n\tprint(f\"It is a {pet['animal']}, called {pet['name'].title()}, \" \n\t\tf\"owned by {pet['owner'].title()}\")","repo_name":"0xEDU/Python-Crash-Course","sub_path":"ch6/pets.py","file_name":"pets.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27265226301","text":"from traditional_cryptography import ciphers as c\nchar_table = {\n 'A':0, 'B':1, 'C':2, 'D':3, 'E':4,\n 'F':5, 'G':6, 'H':7, 'I':8 ,'J':9,\n 'K':10, 'L':11, 'M':12, 'N':13, 'O':14,\n 'P':15, 'Q':16, 'R':17, 'S':18, 'T':19,\n 'U':20, 'V':21, 'W':22, 'X':23, 'Y':24, 'Z':25\n}\n#test affine_encoding\ntest = 'STOPPOLLUTION'\nlength = len(test)\nfor i in range(length):\n num = char_table[test[i]]\n print(c.affine_encoding(17,22,num,26))\n\n#test caesar_decoding\ntest = 'EOXHMHDQV'\nlength = len(test)\nfor i in range(length):\n num = char_table[test[i]]\n print(c.caesar_decoding(num,26))\n\n#test block transposition cipher\ntest = 'GRIZZLYBEARS'\npermutation_list = [3,5,1,2,4]\nprint(c.block_transposition_encoding(permutation_list, test, 5))","repo_name":"HsinTingHo/Practical-Aspects-of-Modern-Cryptography","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38354259025","text":"def sherlockAndAnagrams(string):\n hash_table = dict()\n hashes = dict()\n\n def prime_map(c):\n \"\"\"returns a prime number according to character\"\"\"\n primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101)\n return primes[ord(c) - ord('a')]\n\n def get_hash(s):\n \"\"\"\n :param s:\n :return: returns a hash value for a string\n \"\"\"\n if s in hashes:\n hash_val = hashes[s]\n else:\n hash_val = 1\n for c in s:\n hash_val *= prime_map(c)\n hashes[s] = hash_val\n\n return hash_val\n\n def save_hash(hash_val1, s):\n hash_val = get_hash(s)\n if hash_val1 == hash_val:\n if hash_val in hash_table:\n hash_table[hash_val] += 1\n else:\n hash_table[hash_val] = 1\n\n lenS = len(string)\n for length in range(1, lenS):\n for i in range(0, lenS - length):\n substr1 = string[i:i + length]\n hash1 = get_hash(substr1)\n for j in range(i + 1, lenS - length + 1):\n substr2 = string[j:j + length]\n save_hash(hash1, substr2)\n\n return sum([v for (k, v) in hash_table.items()])\n","repo_name":"subha-py/hackerrank","sub_path":"sherlock_and_anagrams2.py","file_name":"sherlock_and_anagrams2.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7729900226","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndf = pd.read_csv('DataSet_Inova.csv')\r\n\r\nX = 'cetr.uefl.aeg01.velocidadevento'\r\nY = 'cetr.uefl.aeg01.potenciaativa'\r\nplt.plot(df[X],df[Y], 'bo', alpha = 0.2)\r\nplt.xlabel(X + ' [m/s]')\r\nplt.ylabel(Y + ' [kW]')\r\nprint(df.shape)\r\nplt.show()","repo_name":"kaiqueef/inova_desafio","sub_path":"Apenas_PLOT.py","file_name":"Apenas_PLOT.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7796741352","text":"import sys\nsys.path.append('ButtonPressed')\n#import ButtonPressed\n\nfrom flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef main():\n\tprint (\"hello\")\n\treturn render_template('index.html')\n\timport ButtonPressed\n\t\nif __name__ == \"__main__\":\n\tapp.run(host = '0.0.0.0', port=9000, debug=False)\n\t\n","repo_name":"SigridA/ProjectIPCam","sub_path":"FlaskApp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22146180338","text":"\"\"\"\nFunctions for loading CPS microdata into pandas DataFrames using the\nCensus API.\n\"\"\"\n\n\n# Key references:\n# - General workings of the Census API:\n# https://www.census.gov/data/developers/guidance/microdata-api-user-guide.html\n# - Easy way to check available years:\n# https://data.census.gov/mdat/#/\n\n\nimport os\nimport re\nfrom http import HTTPStatus\n\nimport pandas as pd # type: ignore\nimport requests # type: ignore\n\n# Hard code month names since they should not vary by locale\nMONTH_NAME = [\n \"\", # Empty string at 0 so that month number matches month name\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n]\n\n\ndef get_asec(\n year: int,\n variables: list[str],\n) -> pd.DataFrame:\n \"\"\"\n Load CPS ASEC microdata into a pandas DataFrame using the\n Census API.\n\n year: Year of data to retrieve. Years 1992 and on are currently\n supported.\n variables: List of variables to retrieve.\n \"\"\"\n\n key = _get_key() # Get key first to fail fast if it is not found\n\n _check_year(year, min_year=1992)\n\n month = 3 # Month of CPS ASEC is always March\n\n url = _make_url(\"asec\", year, month, variables, key)\n\n df = _get_data(url)\n\n return df\n\n\ndef get_basic(\n year: int,\n month: int,\n variables: list[str],\n) -> pd.DataFrame:\n \"\"\"\n Load basic monthly CPS microdata into a pandas DataFrame using the\n Census API.\n\n year: Year of data to retrieve. Years 1989 and on are currently\n supported.\n month: Month of data to retrieve (specified as a number).\n variables: List of variables to retrieve.\n \"\"\"\n\n key = _get_key()\n\n _check_year(year, min_year=1989)\n\n url = _make_url(\"basic\", year, month, variables, key)\n\n df = _get_data(url)\n\n return df\n\n\ndef _make_url(\n dataset: str,\n year: int,\n month: int,\n variables: list[str],\n key: str,\n) -> str:\n \"\"\"Create URL for Census API request.\"\"\"\n\n _check_month(month)\n _check_variables(variables)\n\n month_abb = MONTH_NAME[month][:3].lower()\n vars_string = \",\".join(variables).upper()\n\n url = (\n \"https://api.census.gov/data/\"\n f\"{year}/cps/{dataset}/{month_abb}?get={vars_string}&key={key}\"\n )\n\n return url\n\n\ndef _get_data(url: str) -> pd.DataFrame:\n \"\"\"Send request to URL and return response content as DataFrame.\"\"\"\n\n headers = {\"user-agent\": \"https://github.com/matt-saenz/PyCPS\"}\n\n resp = requests.get(url, headers=headers)\n\n if resp.status_code != 200:\n # Census API does not (at least currently) supply resp reason\n resp_reason = HTTPStatus(resp.status_code).phrase\n\n raise CensusAPIRequestError(\n f\"Census API request failed [{resp.status_code}]: {resp_reason}\"\n )\n\n if resp.headers[\"content-type\"] != \"application/json;charset=utf-8\":\n raise CensusAPIRequestError(\"Census API did not return JSON\")\n\n raw_data = resp.json()\n\n if not isinstance(raw_data, list):\n raise CensusAPIRequestError(\"Census API data not parsed as expected\")\n\n df = _build_df(raw_data)\n\n return df\n\n\ndef _build_df(raw_data: list[list[str]]) -> pd.DataFrame:\n \"\"\"Build DataFrame out of parsed response content.\"\"\"\n\n col_names = [col_name.lower() for col_name in raw_data[0]]\n cols = raw_data[1:]\n\n df = pd.DataFrame(data=cols, columns=col_names)\n df = df.apply(pd.to_numeric)\n\n return df\n\n\ndef _check_year(year: int, min_year: int) -> None:\n \"\"\"Check if year is valid.\"\"\"\n\n if year < min_year:\n raise ValueError(f\"Years {min_year} and on are currently supported\")\n\n\ndef _check_variables(variables: list[str]) -> None:\n \"\"\"Check if variables list is valid.\"\"\"\n\n if not isinstance(variables, list):\n raise TypeError(\"variables must be a list\")\n\n for var in variables:\n if not isinstance(var, str):\n raise TypeError(\"variables must only contain strings\")\n\n for var in variables:\n if re.search(r\"[^A-Za-z0-9_]\", var):\n raise ValueError(\n \"Elements of variables must only contain letters, digits, and underscores\"\n )\n\n # Ensure all lowercase for dup checking\n variables = [var.lower() for var in variables]\n\n if len(variables) != len(set(variables)):\n raise ValueError(\"variables must not contain any duplicate elements\")\n\n\ndef _check_month(month: int) -> None:\n \"\"\"Check if month is valid.\"\"\"\n\n if not isinstance(month, int):\n raise TypeError(\"month must be an int\")\n\n if month not in range(1, 13):\n raise ValueError(\"month must range from 1 to 12\")\n\n\ndef _get_key() -> str:\n \"\"\"Get user's Census API key.\"\"\"\n\n key = os.getenv(\"CENSUS_API_KEY\")\n\n if key is None:\n raise EnvVarNotFoundError(\n \"You must provide a Census API key by setting env var CENSUS_API_KEY\"\n )\n\n return key\n\n\n# Custom exceptions\n\n\nclass CensusAPIRequestError(Exception):\n \"\"\"Raise if something goes wrong with a Census API request.\"\"\"\n\n\nclass EnvVarNotFoundError(Exception):\n \"\"\"Raise if an environment variable is not found.\"\"\"\n","repo_name":"matt-saenz/PyCPS","sub_path":"src/pycps/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"26520241462","text":"from typing import Any, Type, Union\n\nfrom aioredis import ConnectionsPool, Redis\n\n\nclass MultiExec:\n def __init__(\n self,\n pool_or_connection: ConnectionsPool,\n commands_factory: Type[Redis],\n ):\n ...\n\n def delete(self, key: str) -> Any:\n ...\n\n def hmset(\n self,\n key: str,\n field: Union[str, bytes],\n value: Union[str, bytes],\n *pairs: Union[str, bytes],\n ) -> Any:\n ...\n\n def zadd(\n self, key: str, score: float, member: str, *pairs: Union[float, str]\n ) -> Any:\n ...\n\n async def execute(self, *, return_exceptions: bool = False) -> Any:\n ...\n","repo_name":"dutradda/dbdaora","sub_path":"stubs/aioredis/commands/transaction.pyi","file_name":"transaction.pyi","file_ext":"pyi","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"85"} +{"seq_id":"10695173313","text":"from task import Task\n\nimport os\n\nclass Limit(Task):\n def __init__(self, config = {}):\n super().__init__(config)\n\n def run(self):\n self[\"executable\"] = \"limit\"\n\n self[\"arguments\"] = [\n \"--out-dir\", self[\"dir\"],\n \"--card-dir\", self[\"card-dir\"], \n ]\n\n def output(self):\n self[\"output\"] = self[\"dir\"] + \"/limit.root\"\n\n @staticmethod\n def configure(config, channel, era, cardTasks):\n tasks = []\n\n for mHC in config[\"charged-masses\"]:\n for mh in config[\"neutral-masses\"]:\n cardDir = \"{}/{}/HPlus{}_h{}\".format(os.environ[\"CHDIR\"], config[\"dir\"].replace(\"[E]\", era).replace(\"[C]\", channel), mHC, mh)\n\n limitConf = {\n \"name\": \"Limit_{}_{}_{}_{}\".format(channel, era, mHC, mh), \n \"dir\": \"{}/Limit\".format(cardDir),\n \"card-dir\": cardDir,\n \"display-name\": \"Limit {}/{} ({}/{})\".format(channel, era, mHC, mh), \n \"dependencies\": [t[\"name\"] for t in cardTasks if t[\"dir\"] == cardDir],\n \"channel\": channel,\n \"era\": era\n }\n\n tasks.append(Limit(limitConf))\n\n return tasks\n","repo_name":"cms-desy-charged-higgs/ChargedAnalysis","sub_path":"Analysis/python/limit.py","file_name":"limit.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13347015562","text":"import random\nrandom.seed(10)\nimport string\nimport openpyxl\nimport itertools\nimport pandas as pd\nfrom tqdm import tqdm\nfrom collections import defaultdict\nfrom tabulate import tabulate\nfrom random import shuffle\n\n# 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\nprint('hi')\ndef read_excel_column_to_list(file_path, sheet_name, column, start_row, end_row):\n # Load the workbook and select the desired worksheet\n workbook = openpyxl.load_workbook(file_path)\n worksheet = workbook[sheet_name]\n\n # Read cells from the specified column and row range into a list\n output = [cell.value for cell in worksheet[column][start_row-1:end_row]]\n\n return output, workbook, worksheet\n\nfaculty_names = ['Eng', 'Hum', 'Man', 'Sci']\n\nroom, workbook, worksheet = read_excel_column_to_list('Tables.xlsx', 'Rooms', 'A', 2, 164)\ncapacity, workbook, worksheet = read_excel_column_to_list('Tables.xlsx', 'Rooms', 'B', 2, 164)\n\n##### Normal\nroom, workbook, worksheet = read_excel_column_to_list('Tables.xlsx', 'Rooms', 'A', 2, 164)\ncapacity, workbook, worksheet = read_excel_column_to_list('Tables.xlsx', 'Rooms', 'B', 2, 164)\n\nstudents_per_faculty_year = [[893,1517,714,1339],[766,1302,613,1149],[520,884,416,780],[937,1358,639,1414]]\nnum_courses_list = [[7, 11, 4, 10],[7, 11, 4, 10],[7, 11, 4, 10],[6,13,5,6]]\nnum_assigned_modules = 5\nnum_total_modules = 9\n#num_lectures_list = [3, 2, 2, 3]\nnum_lectures_list = [4, 3, 4, 4]\nyear_percentages = [40, 34, 23, 3]\nnum_teachers_per_faculty =[85,143,68,127]\n\n##### Fast\n# room, workbook, worksheet = read_excel_column_to_list(f'Tables.xlsx', 'Rooms', 'H', 2, 30)\n# capacity, workbook, worksheet = read_excel_column_to_list('Tables.xlsx', 'Rooms', 'I', 2, 30)\n\n# students_per_faculty_year = [[178,303,143,268],[153,260,123,230],[104,176,83,156],[187,271,127,283]]\n# num_courses_list = [[4, 4, 4, 4],[4, 4, 4, 4],[4, 4, 4, 4],[4, 4, 4, 4]]\n# num_lectures_list = [3, 3, 3, 3]\n# year_percentages = [40, 34, 23, 3]\n# num_assigned_modules = 3\n# num_total_modules = 5\n# num_teachers_per_faculty =[20,30,14,25]\n\n##### Instant\n# room, workbook, worksheet = read_excel_column_to_list(f'Tables.xlsx', 'Rooms', 'H', 2, 30)\n# capacity, workbook, worksheet = read_excel_column_to_list('Tables.xlsx', 'Rooms', 'I', 2, 30)\n\n# students_per_faculty_year = [[178,303,143,268],[153,260,123,230],[104,176,83,156],[187,271,127,283]]\n# num_courses_list = [[1, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1]]\n# num_lectures_list = [1, 1, 1, 1]\n# year_percentages = [40, 34, 23, 3]\n# num_assigned_modules = 1\n# num_total_modules = 1\n# num_teachers_per_faculty =[20,30,14,25]\n\n\ndef generate_teacher_work_hours(teacher_id, early_start_prob=0.2, late_start_prob=0.2, working_days=['MON', 'TUE', 'WED', 'THU', 'FRI']):\n start_times = [8, 9, 10]\n \n # Choose start time based on the specified probabilities\n rand_value = random.random()\n if rand_value < early_start_prob:\n start_time = 8\n elif rand_value < late_start_prob:\n start_time = 10\n else:\n start_time = 9\n\n end_time = start_time + 8 # Ensure the teacher works 8 hours per day\n \n work_hours = []\n \n for day in working_days:\n for hour in range(start_time, end_time):\n work_hour = f'{day}{hour:02d}:15'\n if day == 'WED' and hour >= 14: # Skip afternoon hours on Wednesday\n continue\n work_hours.append(work_hour)\n \n return work_hours\n\n\ndef find_students_in_same_module(population, target_module):\n students_in_module = []\n\n for student in population:\n if target_module in student['modules']:\n students_in_module.append(student['name'])\n\n return students_in_module\n\n\n# Comment - Similar to above, like that its a dictionary, but collate this operation with the above one so you only have to loop through student in population once.\ndef count_students_by_faculty(population, faculty_names):\n faculty_counts = {faculty: 0 for faculty in faculty_names}\n\n for student in population:\n faculty_counts[student['faculty']] += 1\n\n return faculty_counts\n\n\ndef count_students_by_faculty_and_year(population, faculty_names, num_years):\n faculty_year_counts = {faculty: {f\"Y{i+1}\": 0 for i in range(num_years)} for faculty in faculty_names}\n\n for student in population:\n faculty_year_counts[student['faculty']][student['year']] += 1\n\n return faculty_year_counts\n\ndef print_table(faculty_year_counts):\n header = \"Faculty/Year\\t\" + \"\\t\".join(f\"Y{i+1}\" for i in range(len(faculty_year_counts[next(iter(faculty_year_counts))])))\n print(header)\n\n for faculty, year_counts in faculty_year_counts.items():\n row = f\"{faculty}\\t\\t\" + \"\\t\".join(str(year_counts[f\"Y{i+1}\"]) for i in range(len(year_counts)))\n print(row)\n\ndef generate_population(students_per_faculty_year, faculty_names, num_courses_list, year_percentages, num_assigned_modules, num_total_modules, num_lectures_list):\n assert len(students_per_faculty_year[0]) == len(faculty_names) == len(num_courses_list[0]) == len(num_lectures_list), \"Length of students_per_faculty_year, faculty_names, num_courses_list, and num_lectures_list must be equal\"\n assert sum(year_percentages) == 100, \"Sum of year_percentages must be equal to 100\"\n\n def generate_unique_id(existing_ids):\n unique_id = ''.join(random.choices(string.ascii_uppercase, k=5))\n while unique_id in existing_ids:\n unique_id = ''.join(random.choices(string.ascii_uppercase, k=5))\n return unique_id\n\n population = []\n unique_ids = set()\n\n for year_idx, year_student_count in enumerate(students_per_faculty_year):\n year = f\"Y{year_idx+1}\"\n\n for idx, (faculty_student_count, faculty_name, num_courses, num_lectures) in enumerate(zip(year_student_count, faculty_names, num_courses_list[year_idx], num_lectures_list)):\n num_students_in_faculty = faculty_student_count\n\n for i in range(num_students_in_faculty):\n course = f\"C{random.randint(1, num_courses)}\"\n unique_id = generate_unique_id(unique_ids)\n unique_ids.add(unique_id)\n student_name = f\"{faculty_name}_{course}_{year}_{unique_id}\"\n\n module_prefix = f\"{faculty_name}_{course}_{year}_M\"\n available_modules = [f\"{module_prefix}{i+1}\" for i in range(num_total_modules)]\n assigned_modules = random.sample(available_modules, num_assigned_modules)\n\n lectures = {}\n for module in assigned_modules:\n module_lectures = [f\"{module}_L{j+1}\" for j in range(num_lectures)]\n lectures[module] = module_lectures\n\n student = {\n 'name': student_name,\n 'faculty': faculty_name,\n 'course': course,\n 'year': year,\n 'unique_id': unique_id,\n 'modules': assigned_modules,\n 'lectures': lectures\n }\n\n population.append(student)\n\n return population\n\n\ndef check_assigned_modules(population, num_assigned_modules):\n incorrect_module_counts = {}\n\n for student in population:\n assigned_module_count = len(student['modules'])\n\n if assigned_module_count != num_assigned_modules:\n incorrect_module_counts[student['name']] = assigned_module_count\n\n if not incorrect_module_counts:\n print(\"All students have the correct number of assigned modules.\")\n else:\n for student_name, module_count in incorrect_module_counts.items():\n print(f\"Student {student_name} has {module_count} assigned modules instead of {num_assigned_modules}.\")\n\n\ndef display_students_in_lecture(population, target_lecture):\n students_in_lecture = []\n\n for student in population:\n for module, lectures in student['lectures'].items():\n if target_lecture in lectures:\n students_in_lecture.append(student['name'])\n break\n\n print(f\"\\nStudents in lecture {target_lecture}:\")\n for student_name in students_in_lecture:\n print(student_name)\n\n\ndef print_unique_modules_and_lectures(population):\n unique_modules = set()\n unique_lectures = set()\n\n for student in population:\n for module in student['modules']:\n unique_modules.add(module)\n for lectures in student['lectures'].values():\n for lecture in lectures:\n unique_lectures.add(lecture)\n print ('')\n print(f\"Total unique modules in the population: {len(unique_modules)}\")\n print(f\"Total unique lectures in the population: {len(unique_lectures)}\")\n\n\ndef get_all_modules(population):\n all_modules = set()\n \n for student in population:\n for module in student['modules']:\n all_modules.add(module)\n \n return list(all_modules)\n\n\ndef assign_modules_to_teachers(population, num_teachers_per_faculty, faculty_names, num_lectures_list, early_start_prob=0.2, late_start_prob=0.2):\n all_modules = get_all_modules(population)\n faculty_modules = {faculty: set() for faculty in faculty_names}\n \n for module in all_modules:\n faculty = module.split('_')[0]\n faculty_modules[faculty].add(module)\n \n teachers = []\n teacher_id = 1\n \n for faculty, num_teachers, num_lectures in zip(faculty_names, num_teachers_per_faculty, num_lectures_list):\n modules = list(faculty_modules[faculty])\n faculty_teachers = []\n\n for i in range(num_teachers):\n teacher = {\n 'teacher_id': teacher_id,\n 'faculty': faculty,\n 'modules': [],\n 'lectures': {},\n 'work_hours': generate_teacher_work_hours(teacher_id, early_start_prob, late_start_prob)\n }\n faculty_teachers.append(teacher)\n teacher_id += 1\n\n for module_idx, module in enumerate(modules):\n teacher_idx = module_idx % num_teachers\n faculty_teachers[teacher_idx]['modules'].append(module)\n\n # Assign lectures to teachers\n module_lectures = [f\"{module}_L{j+1}\" for j in range(num_lectures)]\n faculty_teachers[teacher_idx]['lectures'][module] = module_lectures\n\n teachers.extend(faculty_teachers)\n \n return teachers\n\n\ndef check_module_assignment(population, teachers):\n all_modules = get_all_modules(population)\n assigned_modules = set()\n \n for teacher in teachers:\n for module in teacher['modules']:\n assigned_modules.add(module)\n\n unassigned_modules = set(all_modules) - assigned_modules\n\n if unassigned_modules:\n print(f\"Unassigned modules with students: {unassigned_modules}\")\n return False\n else:\n print(\"All modules with students are assigned to teachers.\")\n return True\n\n\n# Look at doing lecturer profile with prefered hours etc, regular blockers\n\n# ######################### TIME SHIT\n\n# All possible working hours\nall_hours = ['MON08:15', 'MON09:15', 'MON10:15', 'MON11:15', 'MON12:15', 'MON13:15', 'MON14:15', 'MON15:15', 'MON16:15', 'MON17:15', 'MON18:15', 'TUE08:15', 'TUE09:15', 'TUE10:15', 'TUE11:15', 'TUE12:15', 'TUE13:15', 'TUE14:15', 'TUE15:15', 'TUE16:15', 'TUE17:15', 'TUE18:15', 'WED08:15', 'WED09:15', 'WED10:15', 'WED11:15', 'WED12:15', 'WED13:15', 'THU08:15', 'THU09:15', 'THU10:15', 'THU11:15', 'THU12:15', 'THU13:15', 'THU14:15', 'THU15:15', 'THU16:15', 'THU17:15', 'THU18:15', 'FRI08:15', 'FRI09:15', 'FRI10:15', 'FRI11:15', 'FRI12:15', 'FRI13:15', 'FRI14:15', 'FRI15:15', 'FRI16:15', 'FRI17:15', 'FRI18:15']\n#all_hours = ['MON08:15','MON09:15']\n# Times that arent ideal - 8.15 and 18:15\nnonideal_hours = ['MON08:15', 'MON18:15', 'TUE08:15', 'TUE18:15', 'WED08:15', 'THU08:15', 'THU18:15', 'FRI08:15', 'FRI18:15']\n# High Carbon Times\nhighcarbon_hours = ['MON09:15', 'MON16:15', 'MON17:15', 'TUE09:15', 'TUE16:15', 'TUE17:15', 'WED09:15', 'THU09:15', 'THU16:15', 'THU17:15', 'FRI09:15', 'FRI16:15', 'FRI17:15']\n# Low Carbon Times\nlowcarbon_hours = ['MON10:15', 'MON11:15', 'MON12:15', 'MON13:15', 'MON14:15', 'MON15:15', 'TUE10:15', 'TUE11:15', 'TUE12:15', 'TUE13:15', 'TUE14:15', 'TUE15:15', 'WED10:15', 'WED11:15', 'WED12:15', 'WED13:15', 'THU10:15', 'THU11:15', 'THU12:15', 'THU13:15', 'THU14:15', 'THU15:15', 'FRI10:15', 'FRI11:15', 'FRI12:15', 'FRI13:15', 'FRI14:15', 'FRI15:15']\n# Typical 9-15\ntypical_hours = ['MON9:15', 'MON10:15', 'MON11:15', 'MON12:15', 'MON13:15', 'MON14:15', 'MON15:15', 'MON16:15', 'TUE9:15', 'TUE10:15', 'TUE11:15', 'TUE12:15', 'TUE13:15', 'TUE14:15', 'TUE15:15', 'TUE16:15', 'WED9:15', 'WED10:15', 'WED11:15', 'WED12:15', 'WED13:15', 'THU9:15', 'THU10:15', 'THU11:15', 'THU12:15', 'THU13:15', 'THU14:15', 'THU15:15', 'THU16:15', 'FRI9:15', 'FRI10:15', 'FRI11:15', 'FRI12:15', 'FRI13:15', 'FRI14:15', 'FRI15:15', 'FRI16:15']\n# Postgraduate Times\npostgrad_hours = ['WED14:15', 'WED15:15', 'WED16:15', 'WED17:15', 'WED16:15']\n\ndef get_all_lectures(population):\n all_lectures = set()\n\n for student in population:\n for module_lectures in student['lectures'].values():\n all_lectures.update(module_lectures)\n\n return sorted(list(all_lectures))\n\n\ndef get_number_of_students_in_module(population, module):\n count = 0\n for student in population:\n if module in student['modules']:\n count += 1\n return count\n\ndef get_module_faculty(module):\n return module.split('_')[0]\n\n\ndef check_multiple_lectures_same_time(teachers, students, lecture_assignments):\n teacher_timeslots = {}\n student_timeslots = {}\n\n for lecture, assignment in lecture_assignments.items():\n room, time_slot = assignment['room'], assignment['time']\n\n # Check teacher availability\n teacher_id = lecture.split(\"_\")[1]\n teacher_list = [t for t in teachers if t['teacher_id'] == teacher_id]\n\n if not teacher_list:\n return False\n\n teacher = teacher_list[0]\n\n if teacher_id not in teacher_timeslots:\n teacher_timeslots[teacher_id] = []\n\n if time_slot in teacher_timeslots[teacher_id]:\n return False\n\n teacher_timeslots[teacher_id].append(time_slot)\n\n # Check student availability\n module = lecture.split(\"_\")[0]\n students_in_module = get_students_in_module(students, module)\n\n for student in students_in_module:\n student_name = student['name']\n\n if student_name not in student_timeslots:\n student_timeslots[student_name] = []\n\n if time_slot in student_timeslots[student_name]:\n return False\n\n student_timeslots[student_name].append(time_slot)\n\n return True\n\n\ndef get_students_in_module(population, module):\n students_in_module = []\n\n for student in population:\n if module in student['modules']:\n students_in_module.append(student)\n\n return students_in_module\n\n\ndef is_valid_assignment(lecture, room, time, lecture_assignments, teachers, population):\n temp_assignment = lecture_assignments.copy()\n temp_assignment[lecture] = {'room': room, 'time': time}\n\n return check_multiple_lectures_same_time(teachers, population, temp_assignment)\n\n\ndef check_teacher_availability(teacher, lecture_assignments, time_slot):\n for lecture, assignment in lecture_assignments.items():\n if str(teacher['teacher_id']) in lecture and assignment['time'] == time_slot: # Fix: Convert teacher_id to string\n return False\n return True\n\n\n\ndef check_students_availability(module, population, lecture_assignments, time_slot):\n students_in_module = get_students_in_module(population, module)\n\n for student in students_in_module:\n student_lectures = list(itertools.chain(*student['lectures'].values()))\n for lecture in student_lectures:\n if lecture in lecture_assignments and lecture_assignments[lecture]['time'] == time_slot:\n return False\n\n return True\n\n\ndef are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n for student_name in student_names:\n student = next(s for s in population if s['name'] == student_name)\n for module, lectures in student['lectures'].items():\n for lecture in lectures:\n if lecture in lecture_assignments and lecture_assignments[lecture]['time'] == time_slot:\n return False\n\n teacher_id = teacher['teacher_id']\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n if lecture in lecture_assignments and lecture_assignments[lecture]['time'] == time_slot:\n return False\n\n return True\n\ndef are_students_and_teacher_available_v2(population, teachers, teacher, student_names, time_slot, lecture_assignments):\n restricted_slots = ['Mon_11:15', 'Mon_12:15', 'Mon_13:15', 'Mon_14:15']\n\n def check_availability(entity, restricted_slots):\n restricted_slot_count = 0\n for module, lectures in entity['lectures'].items():\n for lecture in lectures:\n if lecture in lecture_assignments and lecture_assignments[lecture]['time'] in restricted_slots:\n restricted_slot_count += 1\n if restricted_slot_count >= 3:\n return False\n if lecture in lecture_assignments and lecture_assignments[lecture]['time'] == time_slot:\n return False\n return True\n\n for student_name in student_names:\n student = next(s for s in population if s['name'] == student_name)\n if not check_availability(student, restricted_slots):\n return False\n\n if not check_availability(teacher, restricted_slots):\n return False\n\n return True\n\n\n\n\n\ndef assign_rooms_and_times_v10(population, teachers, rooms, capacity, all_hours):\n lecture_assignments = {}\n \n # Wrap the outer loop with tqdm\n for teacher in tqdm(teachers, desc=\"Teachers\"):\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n assigned = False\n \n for time_slot in all_hours:\n if assigned:\n break\n \n for room in rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n \n if len(student_names) > capacity[room]:\n continue\n \n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n \n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n \n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\ndef assign_rooms_and_times_v11(population, teachers, rooms, capacity, all_hours):\n lecture_assignments = {}\n \n # Sort rooms by capacity (smallest to largest)\n sorted_rooms = sorted(rooms, key=lambda x: capacity[x])\n\n # Sort teachers' lectures by class size (largest to smallest)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names)))\n sorted_teacher_lectures.sort(key=lambda x: x[3], reverse=True)\n\n for teacher, module, lecture, _ in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n for time_slot in all_hours:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\ndef assign_rooms_and_times_v12(population, teachers, rooms, capacity, optimal_hours, less_optimal_hours, lesser_optimal_hours):\n lecture_assignments = {}\n \n # Sort rooms by capacity (smallest to largest)\n sorted_rooms = sorted(rooms, key=lambda x: capacity[x])\n\n # Sort teachers' lectures by class size (largest to smallest)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names)))\n sorted_teacher_lectures.sort(key=lambda x: x[3], reverse=True)\n\n priority_hours = [optimal_hours, less_optimal_hours, lesser_optimal_hours]\n\n for teacher, module, lecture, _ in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n for priority in priority_hours:\n if assigned:\n break\n\n for time_slot in priority:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\n\ndef assign_rooms_and_times_v13(population, teachers, rooms, capacity, optimal_hours, less_optimal_hours, lesser_optimal_hours):\n lecture_assignments = {}\n \n # Sort rooms by capacity (smallest to largest)\n sorted_rooms = sorted(rooms, key=lambda x: capacity[x])\n\n # Sort teachers' lectures by class size (largest to smallest) and year (higher years first)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n year = int(lecture.split(\"_\")[2][-1])\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names), year))\n sorted_teacher_lectures.sort(key=lambda x: (x[4], x[3]), reverse=True)\n\n priority_hours = [optimal_hours, less_optimal_hours, lesser_optimal_hours]\n\n for teacher, module, lecture, _, _ in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n for priority in priority_hours:\n if assigned:\n break\n\n for time_slot in priority:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\n\ndef assign_rooms_and_times_v15(population, teachers, rooms, capacity, optimal_hours, less_optimal_hours, lesser_optimal_hours):\n lecture_assignments = {}\n \n # Sort rooms by capacity (smallest to largest)\n sorted_rooms = sorted(rooms, key=lambda x: capacity[x])\n\n # Sort teachers' lectures by class size (largest to smallest) and year (higher years first)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n year = int(lecture.split(\"_\")[2][-1])\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names), year))\n sorted_teacher_lectures.sort(key=lambda x: (x[4], x[3]), reverse=True)\n\n priority_hours = [optimal_hours, less_optimal_hours, lesser_optimal_hours]\n\n def get_day(time_slot):\n return time_slot.split(\"_\")[0]\n\n for teacher, module, lecture, _, _ in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n for priority in priority_hours:\n if assigned:\n break\n\n # Group time slots by day\n grouped_time_slots = {day: [time_slot for time_slot in priority if get_day(time_slot) == day] for day in set(get_day(time_slot) for time_slot in priority)}\n\n for day, time_slots in grouped_time_slots.items():\n if assigned:\n break\n\n for time_slot in time_slots:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\ndef assign_rooms_and_times_v16(population, teachers, rooms, capacity, optimal_hours, less_optimal_hours, lesser_optimal_hours):\n lecture_assignments = {}\n\n # Sort rooms by capacity (smallest to largest)\n sorted_rooms = sorted(rooms, key=lambda x: capacity[x])\n\n # Sort teachers' lectures by class size (largest to smallest) and year (higher years first)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n year = int(lecture.split(\"_\")[2][-1])\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names), year))\n sorted_teacher_lectures.sort(key=lambda x: (x[4], x[3]), reverse=True)\n\n priority_hours = [optimal_hours, less_optimal_hours, lesser_optimal_hours]\n\n for teacher, module, lecture, _, _ in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n student_lecture_days = defaultdict(set)\n for la, assignment in lecture_assignments.items():\n for s in population:\n if module in s['lectures'] and la in s['lectures'][module]:\n student_lecture_days[s['name']].add(assignment['time'][:3])\n\n for priority in priority_hours:\n if assigned:\n break\n\n for time_slot in priority:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n # Removed the condition that checks if the new number of days is greater than the current number of days\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\ndef assign_rooms_and_times_v17(population, teachers, rooms, capacity, optimal_hours, less_optimal_hours, lesser_optimal_hours):\n lecture_assignments = {}\n\n # Sort rooms by capacity (smallest to largest)\n # Group rooms by capacity\n rooms_by_capacity = defaultdict(list)\n for room in rooms:\n rooms_by_capacity[capacity[room]].append(room)\n\n # Shuffle rooms within each capacity group and then flatten the list\n sorted_rooms = [room for cap in sorted(rooms_by_capacity.keys()) for room in (shuffle(rooms_by_capacity[cap]) or rooms_by_capacity[cap])]\n # Sort teachers' lectures by class size (largest to smallest) and year (higher years first)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n year = int(lecture.split(\"_\")[2][-1])\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names), year))\n sorted_teacher_lectures.sort(key=lambda x: (x[4], x[3]), reverse=True)\n\n priority_hours = [optimal_hours, less_optimal_hours, lesser_optimal_hours]\n\n for teacher, module, lecture, _, _ in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n student_lecture_days = defaultdict(set)\n for la, assignment in lecture_assignments.items():\n for s in population:\n if module in s['lectures'] and la in s['lectures'][module]:\n student_lecture_days[s['name']].add(assignment['time'][:3])\n\n for priority in priority_hours:\n if assigned:\n break\n\n for time_slot in priority:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n # Removed the condition that checks if the new number of days is greater than the current number of days\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\ndef assign_rooms_and_times_v18(population, teachers, rooms, capacity, optimal_hours, less_optimal_hours, lesser_optimal_hours, postgrad_hours):\n lecture_assignments = {}\n\n # Reorder time slots to start with Wednesday\n def reorder_time_slots(time_slots):\n wed_slots = [slot for slot in time_slots if slot.startswith(\"Wed\")]\n other_slots = [slot for slot in time_slots if not slot.startswith(\"Wed\")]\n return wed_slots + other_slots\n\n optimal_hours = reorder_time_slots(optimal_hours)\n less_optimal_hours = reorder_time_slots(less_optimal_hours)\n lesser_optimal_hours = reorder_time_slots(lesser_optimal_hours)\n postgrad_hours = reorder_time_slots(postgrad_hours)\n\n # Sort rooms by capacity (smallest to largest)\n sorted_rooms = sorted(rooms, key=lambda x: capacity[x])\n\n # Sort teachers' lectures by class size (largest to smallest) and year (higher years first)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n year = int(lecture.split(\"_\")[2][-1])\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names), year))\n sorted_teacher_lectures.sort(key=lambda x: (x[4], x[3]), reverse=True)\n\n for teacher, module, lecture, _, year in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n if year == 4:\n time_slots = postgrad_hours + optimal_hours + less_optimal_hours + lesser_optimal_hours\n else:\n time_slots = optimal_hours + less_optimal_hours + lesser_optimal_hours\n\n for time_slot in time_slots:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available(population, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\n\n\ndef assign_rooms_and_times_v19(population, teachers, rooms, capacity, optimal_hours, less_optimal_hours, lesser_optimal_hours, postgrad_hours):\n lecture_assignments = {}\n\n # Reorder time slots to start with Wednesday\n def reorder_time_slots(time_slots):\n wed_slots = [slot for slot in time_slots if slot.startswith(\"Wed\")]\n other_slots = [slot for slot in time_slots if not slot.startswith(\"Wed\")]\n return wed_slots + other_slots\n\n optimal_hours = reorder_time_slots(optimal_hours)\n less_optimal_hours = reorder_time_slots(less_optimal_hours)\n lesser_optimal_hours = reorder_time_slots(lesser_optimal_hours)\n postgrad_hours = reorder_time_slots(postgrad_hours)\n\n # Sort rooms by capacity (smallest to largest)\n sorted_rooms = sorted(rooms, key=lambda x: capacity[x])\n\n # Sort teachers' lectures by class size (largest to smallest) and year (higher years first)\n sorted_teacher_lectures = []\n for teacher in teachers:\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n year = int(lecture.split(\"_\")[2][-1])\n sorted_teacher_lectures.append((teacher, module, lecture, len(student_names), year))\n sorted_teacher_lectures.sort(key=lambda x: (x[4], x[3]), reverse=True)\n\n for teacher, module, lecture, _, year in tqdm(sorted_teacher_lectures, desc=\"Lectures\"):\n assigned = False\n\n if year == 4:\n time_slots = postgrad_hours + optimal_hours + less_optimal_hours + lesser_optimal_hours\n else:\n time_slots = optimal_hours + less_optimal_hours + lesser_optimal_hours\n\n for time_slot in time_slots:\n if assigned:\n break\n\n for room in sorted_rooms:\n student_names = [s['name'] for s in population if module in s['lectures'] and lecture in s['lectures'][module]]\n\n if len(student_names) > capacity[room]:\n continue\n\n if any(assignment['room'] == room and assignment['time'] == time_slot for assignment in lecture_assignments.values()):\n continue\n\n if not are_students_and_teacher_available_v2(population, teachers, teacher, student_names, time_slot, lecture_assignments):\n continue\n\n lecture_assignments[lecture] = {'room': room, 'time': time_slot}\n assigned = True\n break\n\n return lecture_assignments\n\n\n\n\ndef visualize_assignments(lecture_assignments):\n data = []\n\n for lecture, assignment in lecture_assignments.items():\n module, lecture_num = lecture.rsplit('_', 1)\n room = assignment['room']\n time = assignment['time']\n data.append([module, lecture, lecture_num, room, time])\n\n df = pd.DataFrame(data, columns=['Module', 'Lecture', 'Lecture_Num', 'Room', 'Time'])\n df.sort_values(by=['Module', 'Lecture_Num'], inplace=True)\n return df\n\n\ndef count_unassigned_lectures(lecture_assignments):\n unassigned_count = 0\n for lecture, assignment in lecture_assignments.items():\n if not assignment['room'] or not assignment['time']:\n unassigned_count += 1\n return unassigned_count\n\n\ndef get_all_lectures_from_population(population):\n all_lectures = set()\n for student in population:\n for lectures in student['lectures'].values():\n all_lectures.update(lectures)\n return all_lectures\n\n\ndef count_students_per_lecture(population, lecture_assignments):\n student_counts = {lecture: 0 for lecture in lecture_assignments}\n\n for student in population:\n for module, lectures in student['lectures'].items():\n for lecture in lectures:\n if lecture in student_counts:\n student_counts[lecture] += 1\n else:\n print(f\"Warning: Lecture {lecture} not found in lecture_assignments\")\n\n return student_counts\n\n\ndef get_room_sizes(lecture_assignments, room_capacity):\n room_sizes = {}\n\n for lecture, assignment in lecture_assignments.items():\n room = assignment['room']\n room_sizes[lecture] = room_capacity.get(room, None)\n\n return room_sizes\n\n\ndef check_room_capacity(lecture_student_counts, lecture_room_sizes):\n insufficient_rooms = []\n rooms_not_found = []\n\n for lecture, student_count in lecture_student_counts.items():\n room_size = lecture_room_sizes.get(lecture, None)\n\n if room_size is None:\n rooms_not_found.append(lecture)\n elif room_size < student_count:\n insufficient_rooms.append((lecture, room_size, student_count))\n\n if not insufficient_rooms and not rooms_not_found:\n print(\"All rooms sufficiently sized\")\n else:\n if insufficient_rooms:\n print(\"Insufficient room capacities:\")\n for lecture, room_size, student_count in insufficient_rooms:\n print(f\"{lecture}: Capacity: {room_size}, Students: {student_count}\")\n print()\n\n if rooms_not_found:\n print(\"Rooms not found:\")\n for lecture in rooms_not_found:\n print(f\"{lecture}\")\n print()\n\n\ndef check_room_allocations(lecture_assignments):\n timeslot_rooms = {}\n\n for lecture, assignment in lecture_assignments.items():\n room = assignment['room']\n time = assignment['time']\n\n if time not in timeslot_rooms:\n timeslot_rooms[time] = set()\n\n if room in timeslot_rooms[time]:\n print(f\"Room {room} has been allocated more than once at timeslot {time}\")\n return False\n else:\n timeslot_rooms[time].add(room)\n\n print(\"All rooms allocated only once per timeslot\")\n return True\n\ndef check_allocations(population, teachers, lecture_assignments):\n student_timeslots = {}\n teacher_timeslots = {}\n\n clashes_found = False\n\n for student in population:\n student_name = student['name']\n for module, lectures in student['lectures'].items():\n for lecture in lectures:\n time = lecture_assignments[lecture]['time']\n\n if student_name not in student_timeslots:\n student_timeslots[student_name] = {}\n\n if time in student_timeslots[student_name] and student_timeslots[student_name][time] != lecture:\n print(f\"Student {student_name} has more than one lecture at timeslot {time}\")\n print(f\"Current lecture: {lecture}, Previous lecture: {student_timeslots[student_name][time]}\")\n clashes_found = True\n else:\n student_timeslots[student_name][time] = lecture\n\n for teacher in teachers:\n teacher_id = teacher['teacher_id']\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n time = lecture_assignments[lecture]['time']\n\n if teacher_id not in teacher_timeslots:\n teacher_timeslots[teacher_id] = {}\n\n if time in teacher_timeslots[teacher_id] and teacher_timeslots[teacher_id][time] != lecture:\n print(f\"Teacher {teacher_id} has more than one lecture at timeslot {time}\")\n print(f\"Current lecture: {lecture}, Previous lecture: {teacher_timeslots[teacher_id][time]}\")\n clashes_found = True\n else:\n teacher_timeslots[teacher_id][time] = lecture\n\n if not clashes_found:\n print(\"No clashes found\")\n\n return student_timeslots, teacher_timeslots, not clashes_found\n\n\ndef get_unassigned_room_timeslots(lecture_assignments, rooms, time_slots):\n assigned_room_times = {}\n for assignment in lecture_assignments.values():\n room_time = (assignment['room'], assignment['time'])\n assigned_room_times[room_time] = True\n\n unassigned_room_timeslots = {}\n for room in rooms:\n unassigned_times = []\n for time_slot in time_slots:\n if (room, time_slot) not in assigned_room_times:\n unassigned_times.append(time_slot)\n unassigned_room_timeslots[room] = unassigned_times\n\n return unassigned_room_timeslots\n\n\ndef count_days_at_university(student_timeslots, student_name):\n days = set()\n \n for time_slot in student_timeslots[student_name]:\n day = time_slot[:3]\n days.add(day)\n \n return len(days)\n\n\ndef average_days_per_faculty_and_university(population, student_timeslots):\n faculty_year_days = defaultdict(lambda: defaultdict(lambda: {'students': 0, 'total_days': 0}))\n university_year_days = defaultdict(lambda: {'students': 0, 'total_days': 0})\n\n for student in population:\n student_name = student['name']\n faculty = student['faculty']\n year = student['year']\n\n days_at_university = count_days_at_university(student_timeslots, student_name)\n\n faculty_year_days[faculty][year]['students'] += 1\n faculty_year_days[faculty][year]['total_days'] += days_at_university\n\n university_year_days[year]['students'] += 1\n university_year_days[year]['total_days'] += days_at_university\n\n faculty_year_averages = {\n faculty: {year: info['total_days'] / info['students'] for year, info in year_info.items()}\n for faculty, year_info in faculty_year_days.items()\n }\n university_year_averages = {\n year: info['total_days'] / info['students'] for year, info in university_year_days.items()\n }\n\n # Print the table\n unique_years = sorted(set(student['year'] for student in population))\n sorted_faculties = sorted(faculty_year_averages.keys())\n print('')\n print('Average number of days spent on campus per year and faculty')\n header = \"Faculty\\t\" + \"\\t\".join(unique_years)\n print(header)\n\n for faculty in sorted_faculties:\n year_averages = faculty_year_averages[faculty]\n row = f\"{faculty}\\t\" + \"\\t\".join(f\"{year_averages.get(year, 0):.2f}\" for year in unique_years)\n print(row)\n\n # Print the 'All' row for the entire university\n print('All\\t' + \"\\t\".join(f\"{university_year_averages.get(year, 0):.2f}\" for year in unique_years))\n print('')\n\n return faculty_year_averages\n\n\ndef lecture_count_per_time_and_year_v4(lecture_assignments):\n time_year_count = defaultdict(lambda: defaultdict(int))\n\n for lecture, assignment in lecture_assignments.items():\n time = assignment['time'][-5:]\n year = \"Y\" + lecture.split(\"_\")[2][-1]\n\n time_year_count[time][year] += 1\n\n # Find all unique years in the data\n unique_years = sorted(set(year for year_counts in time_year_count.values() for year in year_counts.keys()))\n\n # Sort the times in ascending order\n sorted_times = sorted(time_year_count.keys(), key=lambda x: (int(x.split(':')[0]), int(x.split(':')[1])))\n\n # Print the table\n header = \"Time\\t\" + \"\\t\".join(unique_years)\n print(header)\n\n for time in sorted_times:\n year_counts = time_year_count[time]\n row = f\"{time}\\t\" + \"\\t\".join(str(year_counts[year]) for year in unique_years)\n print(row)\n\ndef lecture_count_per_day_and_time(lecture_assignments):\n day_time_count = defaultdict(lambda: defaultdict(int))\n\n for lecture, assignment in lecture_assignments.items():\n day = assignment['time'][:3]\n time = assignment['time'][3:]\n\n day_time_count[day][time] += 1\n\n # Find all unique days and times in the data\n day_order = ['MON', 'TUE', 'WED', 'THU', 'FRI']\n unique_days = sorted(set(day for day in day_time_count.keys()), key=lambda x: day_order.index(x))\n unique_times = sorted(set(time for time_counts in day_time_count.values() for time in time_counts.keys()))\n\n # Print the table\n header = \"Time\\t\" + \"\\t\".join(unique_days)\n print(header)\n\n for time in unique_times:\n row = f\"{time}\\t\" + \"\\t\".join(str(day_time_count[day][time]) for day in unique_days)\n print(row)\n\n\ndef count_students_without_breaks(lecture_assignments):\n students_without_breaks = 0\n\n for s in population:\n student_lecture_times = defaultdict(list)\n\n for module, lecture in s['lectures'].items():\n for la in lecture:\n if la in lecture_assignments:\n time_slot = lecture_assignments[la]['time']\n day, time = time_slot.split()\n student_lecture_times[day].append(time)\n\n for day, times in student_lecture_times.items():\n times = sorted(times)\n has_continuous_lectures = False\n\n for i in range(len(times) - 3):\n if times[i] == \"11:15\" and times[i + 1] == \"12:15\" and times[i + 2] == \"13:15\" and times[i + 3] == \"14:15\":\n has_continuous_lectures = True\n break\n\n if has_continuous_lectures:\n students_without_breaks += 1\n break\n\n return students_without_breaks\n\n####### OUTPUT\npopulation = generate_population(students_per_faculty_year, faculty_names, num_courses_list, year_percentages, num_assigned_modules, num_total_modules, num_lectures_list)\n\n# Finding students in the same module\ntarget_module = 'Man_C1_Y4_M3'\nstudents_in_module = find_students_in_same_module(population, target_module)\n\nprint(f\"\\nStudents in module {target_module}:\")\nfor student_name in students_in_module:\n print(student_name)\n\nprint(len(population))\n\ncheck_assigned_modules(population, num_assigned_modules)\n\n# Count students per faculty and print the results\nfaculty_counts = count_students_by_faculty(population, faculty_names)\n\nprint(\"Number of students per faculty:\")\nfor faculty, count in faculty_counts.items():\n print(f\"{faculty}: {count}\")\n\n\n# Count students per faculty and year and print the table\nfaculty_year_counts = count_students_by_faculty_and_year(population, faculty_names, len(year_percentages))\nprint(\"\\nNumber of students per faculty per year:\")\nprint_table(faculty_year_counts)\n\n# Example usage:\n#display_students_in_lecture(population, \"Man_C1_Y4_M3_L1\")\n#display_students_in_lecture(population, \"Man_C1_Y4_M3_L2\")\n\nprint_unique_modules_and_lectures(population)\n\nall_modules = get_all_modules(population)\nprint(len(all_modules))\n\nteachers = assign_modules_to_teachers(population, num_teachers_per_faculty, faculty_names, num_lectures_list)\n\n# Assuming the previously generated population and teachers\nmodule_assignment_check = check_module_assignment(population, teachers)\n\n#print(teachers)\n\nprint(module_assignment_check)\n#print(len(teachers))\n\n#print(len(get_all_lectures(population)))\n\nstudent_occupied_time_slots = {student['name']: set() for student in population}\nteacher_occupied_time_slots = {teacher['teacher_id']: set() for teacher in teachers}\n\nroom_capacity_dict = dict(zip(room, capacity))\n\n\n\n\n\n\n#lecture_assignments = assign_rooms_and_times_v10(population, teachers, room, room_capacity_dict, all_hours)\n#lecture_assignments = assign_rooms_and_times_v11(population, teachers, room, room_capacity_dict, all_hours)\n#lecture_assignments = assign_rooms_and_times_v12(population, teachers, room, room_capacity_dict, lowcarbon_hours, highcarbon_hours, nonideal_hours)\n#lecture_assignments = assign_rooms_and_times_v13(population, teachers, room, room_capacity_dict, lowcarbon_hours, highcarbon_hours, nonideal_hours)\n#lecture_assignments = assign_rooms_and_times_v16(population, teachers, room, room_capacity_dict, lowcarbon_hours, highcarbon_hours, nonideal_hours)\n#lecture_assignments = assign_rooms_and_times_v17(population, teachers, room, room_capacity_dict, lowcarbon_hours, highcarbon_hours, nonideal_hours)\n#lecture_assignments = assign_rooms_and_times_v18(population, teachers, room, room_capacity_dict, lowcarbon_hours, highcarbon_hours, nonideal_hours, postgrad_hours)\nlecture_assignments = assign_rooms_and_times_v19(population, teachers, room, room_capacity_dict, lowcarbon_hours, highcarbon_hours, nonideal_hours, postgrad_hours)\n\n\n\nwith open(\"lecture_assignments.txt\", \"w\") as file:\n for lecture, assignment in lecture_assignments.items():\n file.write(f\"{lecture}: {assignment}\\n\")\n\n\n\n#print(lecture_assignments)\n\ndf = visualize_assignments(lecture_assignments)\nprint(df)\n\ndf.to_excel('TimeTable.xlsx', index=False)\n\nunassigned_lectures = count_unassigned_lectures(lecture_assignments)\nprint(f\"Number of unassigned lectures: {unassigned_lectures}\")\n\n# all_lectures = get_all_lectures_from_population(population)\n# print(\"All lectures from population:\")\n# print(all_lectures)\n\n# assigned_lectures = set(lecture_assignments.keys())\n# print(\"Assigned lectures:\")\n# print(assigned_lectures)\n\n# missing_lectures = all_lectures - assigned_lectures\n# print(\"Missing lectures:\")\n# print(missing_lectures)\n\nstudents_per_lecture = count_students_per_lecture(population, lecture_assignments)\n\n#print(\"Number of students per lecture:\")\n#for lecture, count in students_per_lecture.items():\n# print(f\"{lecture}: {count}\")\n\nroom_capacity_dict = {room: capacity for room, capacity in zip(room, capacity)}\n\n# print(room_capacity_dict)\n\nlecture_room_sizes = get_room_sizes(lecture_assignments, room_capacity_dict)\n# print(\"Room sizes for lectures:\")\n# for lecture, room_size in lecture_room_sizes.items():\n# if room_size is None:\n# print(f\"{lecture}: Room not found\")\n# else:\n# print(f\"{lecture}: {room_size}\")\n\n# Call the function with the lecture_student_counts and lecture_room_sizes dictionaries\ncheck_room_capacity(students_per_lecture, lecture_room_sizes)\n\n# Call the function with the population, teachers, and lecture_assignments dictionaries\nstudent_timeslots, teacher_timeslots, allocation_check = check_allocations(population, teachers, lecture_assignments)\n\n# unassigned_room_timeslots = get_unassigned_room_timeslots(lecture_assignments, room, all_hours)\n# print(\"Unassigned room timeslots:\")\n# for room, times in unassigned_room_timeslots.items():\n# print(f\"{room}: {times}\")\n\n\n# Example usage\n# student_name = \"Man_C3_Y4_MP\" # Replace with the student name you want to check\n# days_at_university = count_days_at_university(student_timeslots, student_name)\n# print(f\"{student_name} spends {days_at_university} days at university.\")\n\n# Example usage\nfaculty_year_averages = average_days_per_faculty_and_university(population, student_timeslots)\n\n\n\n# Create a DataFrame for student lecture times\nstudent_data = []\n\nfor student in population:\n student_name = student['name']\n for module, lectures in student['lectures'].items():\n for lecture in lectures:\n time = lecture_assignments[lecture]['time']\n room = lecture_assignments[lecture]['room']\n student_data.append([student_name, module, lecture, room, time])\n\nstudent_df = pd.DataFrame(student_data, columns=['Student', 'Module', 'Lecture', 'Room', 'Time'])\nstudent_df.sort_values(by=['Student', 'Time'], inplace=True)\n\n# Create a DataFrame for teacher lecture times\nteacher_data = []\n\nfor teacher in teachers:\n teacher_id = teacher['teacher_id']\n for module, lectures in teacher['lectures'].items():\n for lecture in lectures:\n time = lecture_assignments[lecture]['time']\n room = lecture_assignments[lecture]['room']\n teacher_data.append([teacher_id, module, lecture, room, time])\n\nteacher_df = pd.DataFrame(teacher_data, columns=['Teacher', 'Module', 'Lecture', 'Room', 'Time'])\nteacher_df.sort_values(by=['Teacher', 'Time'], inplace=True)\n\n# Export the DataFrames to Excel sheets in the same file\nwith pd.ExcelWriter('lecture_times.xlsx') as writer:\n student_df.to_excel(writer, sheet_name='Students', index=False)\n teacher_df.to_excel(writer, sheet_name='Teachers', index=False)\n\nlecture_count_per_time_and_year_v4(lecture_assignments)\n\nused_rooms_per_day = defaultdict(set)\n\nfor assignment in lecture_assignments.values():\n day = assignment['time'][:3]\n used_rooms_per_day[day].add(assignment['room'])\n\nfor day, rooms in used_rooms_per_day.items():\n print(f\"Number of rooms used on {day}: {len(rooms)}\")\n\n\nlecture_count_per_day_and_time(lecture_assignments)\n\n\n\nprint('hi')\n\ndef count_students_without_breaks_per_day(lecture_assignments):\n students_without_breaks = defaultdict(int, {'MON': 0, 'TUE': 0, 'WED': 0, 'THU': 0, 'FRI': 0, 'ALL': 0})\n\n for s in population:\n student_lecture_times = defaultdict(list)\n\n for module, lecture in s['lectures'].items():\n for la in lecture:\n if la in lecture_assignments:\n time_slot = lecture_assignments[la]['time']\n day, time = time_slot[:2], time_slot[2:]\n student_lecture_times[day].append(time)\n\n for day, times in student_lecture_times.items():\n times = sorted(times)\n has_continuous_lectures = False\n\n for i in range(len(times) - 3):\n if times[i] == \"11:15\" and times[i + 1] == \"12:15\" and times[i + 2] == \"13:15\" and times[i + 3] == \"14:15\":\n has_continuous_lectures = True\n break\n\n if has_continuous_lectures:\n students_without_breaks[day] += 1\n students_without_breaks['ALL'] += 1\n\n return students_without_breaks\n\nstudents_without_breaks_per_day = count_students_without_breaks_per_day(lecture_assignments)\nprint(\"Students without breaks between 11:15 and 15:15 per day (including total):\", students_without_breaks_per_day)\n\n","repo_name":"DPBath/Environmental-Timetable","sub_path":"population.py","file_name":"population.py","file_ext":"py","file_size_in_byte":56897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17133847015","text":"#Exercise_35\r\nclass WrongError (Exception):\r\n pass\r\nclass Check (WrongError):\r\n def Find(self):\r\n a = input(\"please Enter Your File Address: \")\r\n b = \"\"\r\n if a.lower() == \"end\":\r\n return exit(0)\r\n try:\r\n with open (a) as f:\r\n l = f.readlines()\r\n Freecount = 0\r\n b = input(\"please Enter Your Word That You looking For: \")\r\n if b.lower() == \"end\":\r\n exit(0)\r\n wordCount = 0\r\n for val in l :\r\n if \"free\" in val.lower():\r\n Freecount += val.count(\"free\")\r\n if b in val :\r\n\r\n wordCount += val.count(b)\r\n print (\"----------------------------\")\r\n print (f\" {b} in Text: {wordCount} Times!\")\r\n try:\r\n if Freecount > 0 :\r\n raise WrongError \r\n except WrongError as WR:\r\n print (f\"\"\" WrongWord Error \r\n--------------------------- \r\nWe Have Found \\'Free\\' \r\nin your File {Freecount} Times!\r\n---------------------------\"\"\")\r\n except:\r\n if b.lower() == \"end\":\r\n exit(0)\r\n print(\"Oops file Doesnt Found, please Try Again\")\r\n self.Find()\r\n\r\n\r\na= Check()\r\n# a.Find()","repo_name":"Amirmahdikahdouii/Final-Project","sub_path":"Final/Modules/exercise35.py","file_name":"exercise35.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"43600625116","text":"from flaskr import db\n\ntables = {}\ntables['users'] = (\n \"CREATE TABLE `users` (\"\n \" `id` int PRIMARY KEY AUTO_INCREMENT,\"\n \" `username` varchar(30) UNIQUE NOT NULL,\"\n \" `passwd` varchar(30) NOT NULL\"\n \")\"\n)\n\ntables['todos'] = (\n \"CREATE TABLE `todos` (\"\n \" `id` int PRIMARY KEY AUTO_INCREMENT,\"\n \" `author` varchar(30) NOT NULL,\"\n \" `created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\"\n \" `task` TEXT NOT NULL\"\n \")\"\n)\n\ndef create_schema():\n for table in tables:\n table_schema = tables[table]\n print(\"Creating table {}: \".format(table), end='')\n db.createTables(table_schema)\n\n\n","repo_name":"azubuikeokom/python-todo-app","sub_path":"backend/flaskr/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31773087779","text":"# https://leetcode.com/problems/combinations/\n\n# Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].\n#\n# You may return the answer in any order.\nfrom typing import List\n\nn = 4\nk = 2\n\n# Output:\n# [\n# [2,4],\n# [3,4],\n# [2,3],\n# [1,2],\n# [1,3],\n# [1,4],\n# ]\n\nn = 1\nk = 1\n\n# Output: [[1]]\n\n\n# dfs\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n\n result_list = []\n\n def dfs(temp_list:List, last_list:list):\n if len(temp_list) == k:\n result_list.append(temp_list[:])\n return\n\n for i in range(len(last_list)):\n # 임시 리스트에 담아준다.\n temp_list.append(last_list[i])\n # 잔여 리스트 생성\n temp = last_list[i+1:]\n # dfs\n dfs(temp_list, temp)\n # 기존 임시 리스트 삭제\n temp_list.remove(last_list[i])\n\n dfs([], [x for x in range(1,n+1)])\n\n return result_list\n\nprint(Solution().combine(n,k))\n\n# combination\n\nfrom itertools import combinations\n\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return list(map(list, combinations(range(1,n+1),k)))\n\n\nprint(Solution().combine(n,k))\n\n","repo_name":"jihuncha/Data_Structure","sub_path":"com/codingTest/reminder/algorithm_interview_remind/chap12_graph/combinations.py","file_name":"combinations.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"3296511136","text":"#!/usr/bin/env python\n\"\"\"\nAuthor: Sarucha Yanyong\nPurpose: Remote control turtlebot3\nRevision:\n1.0 2019-07-10 Baseline\n\"\"\"\n\nimport sys\nimport subprocess\nimport os\nimport paramiko\nimport socket\nimport re\nimport time\nimport ConfigParser\n\n\n\ndef ping(hostname):\n # hostname = \"google.com\" #example\n response = os.system(\"ping -c 1 \" + hostname)\n if response == 0:\n print (\"Ping: Destination is UP\")\n return True\n else:\n print (\"Ping: Destination is Down\")\n return False\n\ndef send(channel, command=None, live=True, once=False, end=None):\n buff = \"\"\n _resp = \"\"\n start = time.time()\n if command != None:\n channel.send(command + '\\n')\n if once:\n return \"shutdown\"\n \n if end is None:\n end = \":~$ \"\n \n while not buff.endswith(end):\n resp = channel.recv(9999)\n buff += str(resp)\n print(\">>\" + str(buff[-20:]) + \"<<\")\n\n # if str(resp) != _resp: # Detect changing\n # start = time.time()\n # _resp = str(resp)\n\n if live:\n print(str(resp) + \"\\n\")\n # print(buff)\n # print(\"OUT\")\n return buff\n\ndef is_valid_ip(ip):\n m = re.match(r\"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$\", ip)\n return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))\n\ndef main():\n config = ConfigParser.ConfigParser()\n config.sections()\n config.read('ipconfig.ini')\n\n print(\"Python version\")\n print (sys.version)\n print(\"Version info.\")\n print (sys.version_info)\n\n \n\n # cliend_ip = input(\"Client IP Address: \").strip()\n master_ip = cliend_ip = None\n # cliend_ip = \"192.168.10.207\"\n # master_ip = \"192.168.10.238\"\n\n master_ip = config.get('DEFAULT', 'PC_IP')\n cliend_ip = config.get('DEFAULT', 'TURTLEBOT_IP')\n\n if len(sys.argv) >= 2:\n if is_valid_ip(sys.argv[1]) and is_valid_ip(sys.argv[2]):\n master_ip = sys.argv[1]\n cliend_ip = sys.argv[2]\n if master_ip is None and cliend_ip is None:\n master_ip = raw_input(\"Computer IP Address: \").strip()\n cliend_ip = raw_input(\"TurtleBot IP Address: \").strip()\n \n print(\"Connect %s to %s\" % (master_ip, cliend_ip))\n\n\n if not is_valid_ip(cliend_ip) or not is_valid_ip(master_ip):\n print(\"Wrong IP Address format.\")\n sys.exit(0)\n\n\n mode = raw_input(\"\"\"\n Options\n =========\n [1] Check turtlebot connection.\n [2] Bringup Turtlebot\n [3] Remote shutdown Turtlebot\n [4] Remote restart Turtlebot\n \"\"\"\n ).strip()\n \n if mode == \"1\":\n print(\"Alive.\" if ping(cliend_ip) else \"Lost connection.\")\n\n elif mode == \"3\":\n if ping(cliend_ip):\n remote = None\n try:\n remote = paramiko.SSHClient()\n remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n remote.connect(cliend_ip, username=\"pi\", password=\"raspberry\")\n\n channel = remote.invoke_shell()\n send(channel)\n print(send(channel, command=\"sudo shutdown now\", once=True))\n print(send(channel, command=\"raspberry\", once=True))\n except Exception as e:\n print('Connection Failed')\n print(e)\n finally:\n print (\"Close\")\n if remote:\n remote.close()\n\n while ping(cliend_ip):\n print(\"Shunting down...\")\n time.sleep(1)\n print(\"Robot has been shutdown completely.\")\n\n elif mode == \"4\":\n if ping(cliend_ip):\n remote = None\n try:\n remote = paramiko.SSHClient()\n remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n remote.connect(cliend_ip, username=\"pi\", password=\"raspberry\")\n\n channel = remote.invoke_shell()\n send(channel)\n print(send(channel, command=\"sudo reboot\", once=True))\n print(send(channel, command=\"raspberry\", once=True))\n except Exception as e:\n print('Connection Failed')\n print(e)\n finally:\n print (\"Close\")\n if remote:\n remote.close()\n\n while ping(cliend_ip):\n print(\"Shunting down...\")\n time.sleep(1)\n while not ping(cliend_ip):\n print(\"Booting up...\")\n time.sleep(1)\n print(\"Robot has been reboot completely.\")\n\n elif mode == \"2\":\n if ping(cliend_ip):\n print(cliend_ip)\n remote = None\n try:\n remote = paramiko.SSHClient()\n remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n remote.connect(cliend_ip, username=\"pi\", password=\"raspberry\")\n\n channel = remote.invoke_shell()\n send(channel)\n print(send(channel, command=\"export ROS_MASTER_URI=http://%s:11311\" % master_ip))\n print(send(channel, command=\"export ROS_HOSTNAME=%s\" % cliend_ip))\n print(send(channel, command=\"env | grep \\\"ROS\\\"\"))\n print(send(channel, command=\"echo $ROS_MASTER_URI\"))\n print(send(channel, command=\"roslaunch turtlebot3_bringup turtlebot3_robot.launch\", \n end=\": Calibration End\\r\\n\"))\n\n raw_input(\"Enter to exit...\")\n print(send(channel, command=\"\\x03\", once=True))\n sys.exit()\n except Exception as e:\n print('Connection Failed')\n print(e)\n finally:\n print (\"Close\")\n if remote:\n remote.close()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"syanyong/turtlebot3_support_scripts","sub_path":"launch_my_turtlebot.py","file_name":"launch_my_turtlebot.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31393074248","text":"# Dictionary\n# Dictionaries are used to store data values in key:value pairs.\n\n# A dictionary is a collection which is ordered*, changeable and do not allow duplicates.\n# Dictionaries are written with curly brackets, and have keys and values:\n\n# Dictionary Items\n# Dictionary items are ordered, changeable, and does not allow duplicates.\n\n# Dictionary items are presented in key:value pairs, and can be referred to by using the key name.\n\n# Print the \"brand\" value of the dictionary:\ndict_1 = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\nprint(\"dict_1: \", dict_1)\nprint(\"brand: \", dict_1[\"brand\"])\n\n# Ordered or Unordered?\n# As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.\n\n# When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.\n\n# Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.\n\n# Changeable\n# Dictionaries are changeable, meaning that we can change, add or remove \n# items after the dictionary has been created.\n\n# Duplicates Not Allowed\n# Dictionaries cannot have two items with the same key:\n\n# Duplicate values will overwrite existing values:\n\ndict_2 = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964,\n \"year\": 2020\n}\nprint(dict_2) # {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}\n\n# Dictionary Items - Data Types\n# The values in dictionary items can be of any data type:\n\n# String, int, boolean, and list data types:\ndict_3 = {\n \"brand\": \"Ford\",\n \"electric\": False,\n \"year\": 1964,\n \"colors\": [\"red\", \"white\", \"blue\"]\n}\nprint(\"dict_3:\", dict_3) #{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}\n\n# The dict() Constructor\n# It is also possible to use the dict() constructor to make a dictionary.\n\n# Using the dict() method to make a dictionary:\ndict_4 = dict(name = \"John\", age = 36, country = \"Norway\")\nprint(\"dict_4: \", dict_4)\n\n# Accessing Items\n# You can access the items of a dictionary by \n# referring to its key name, inside square brackets:\n\n# Get the value of the \"model\" key:\ndict_5 = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\nprint('dict_5: ', type(dict_5));\nx = dict_5[\"model\"]\nprint('x: ', x); # Mustang\n\n# There is also a method called get() that will give you the same result:\n\n# Get the value of the \"model\" key:\nxx = dict_5.get(\"brand\")\nprint('xx: ', xx); # Ford\n\n# Get Keys\n# The keys() method will return a list of all the keys in the dictionary.\n\nget_keys = dict_5.keys()\nprint('get_keys: ', get_keys); # dict_keys(['brand', 'model', 'year'])\n\n\n# Get Values\n# The values() method will return a list of all the values in the dictionary.\n\n\n# Get a list of the values:\ndict_5_value = dict_5.values()\nprint('dict_5_value: ', dict_5_value); # dict_values(['Ford', 'Mustang', 1964])\nprint(type(dict_5_value))\n\n# Get Items\n# The items() method will return each item in a dictionary, as tuples in a list.\n\n# Get a list of the key:value pairs\ndict_5_items = dict_5.items()\nprint('dict_5_items: ', dict_5_items); # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])\n\n# Check if Key Exists\n# To determine if a specified key is present in a dictionary use the in keyword:\n\ndict_6 = {\n \"brand\": \"namX\",\n \"model\": \"v1\",\n \"year\": 2023\n}\nif \"brand\" in dict_6:\n print(\"Yes, 'brand' is one of the keys in the dict_6 dictionary\")\n\n# Change Values\n# You can change the value of a specific item by referring to its key name:\n\n# Change the \"year\" to 2024:\ndict_6[\"year\"] = 2024\nprint(dict_6.get('year'))\n\n# Update Dictionary\n# The update() method will update the dictionary with the items from the given argument.\n\n# The argument must be a dictionary, or an iterable object with key:value pairs.\n\n# Update the \"model\" of the car by using the update() method:\ndict_6.update({'model': 'v2'})\nprint(\"dict_6: \", dict_6)\n\n# Adding Items\n# Adding an item to the dictionary is done by using \n# a new index key and assigning a value to it:\ndict_7 = {\n \"brand\": \"Neo\",\n \"model\": \"v1\",\n \"year\": 2023\n}\ndict_7[\"color\"] = \"red\"\nprint(\"dict_7: \", dict_7)\n\n# Update Dictionary\n# The update() method will update the dictionary with the \n# items from a given argument. If the item does not exist, the item will be added.\n\n# The argument must be a dictionary, or an iterable object with key:value pairs.\ndict_7.update({\"color\": \"Green\"})\ndict_7.update({\"price\": 300000})\nprint(\"updated dict_7: \", dict_7)\n\n# Removing Items\n# There are several methods to remove items from a dictionary:\n\n# The pop() method removes the item with the specified key name:\ndict_8 = {\n \"name\": \"Baba\",\n \"age\": 47,\n \"job\": \"developer\",\n \"hobby\": \"yoga\"\n}\ndict_8.pop(\"hobby\")\nprint(\"dict_8: \", dict_8)\n\n# The popitem() method removes the last inserted item (\n# in versions before 3.7, a random item is removed instead):\ndict_9 = {\n \"name\": \"Jaja\",\n \"age\": 30,\n \"hobby\": \"photography\",\n \"job\": \"barber\",\n}\ndict_9.popitem()\nprint(\"dict_9: \", dict_9)\n\n# The del keyword removes the item with the specified key name:\n# The del keyword can also delete the dictionary completely: del dict_10\ndict_10 = {\n \"name\": \"Fafa\",\n \"age\": 50,\n \"hobby\": \"cinema\",\n \"job\": \"policeman\",\n}\ndel dict_10[\"age\"]\nprint(\"dict_10: \", dict_10)\n\n# The clear() method empties the dictionary:\ndict_11 = {\n \"name\": \"haja\",\n \"age\": 70,\n \"hobby\": \"stamps collection\",\n \"job\": \"fisherman\",\n}\ndict_11.clear()\nprint(\"dict_11: \", dict_11)\n\n\n# Loop Through a Dictionary\n# You can loop through a dictionary by using a for loop.\n\n# When looping through a dictionary, the return value are the keys of \n# the dictionary, but there are methods to return the values as well.\n\n# print all key names in the dictionary, one by one:\ndict_12 = {\n \"name\": \"Zaza\",\n \"age\": 49,\n \"hobby\": \"sport\",\n \"job\": \"fireman\",\n}\nfor x in dict_12:\n print(x) # name age hobby job\n# You can use the keys() method to return the keys of a dictionary:\nfor x in dict_12.keys():\n print(x) # name age hobby job\n\n# Print all values in the dictionary, one by one:\nfor x in dict_12:\n print(dict_12[x]) # Zaza 49 sport fireman\n# You can also use the values() method to return values of a dictionary:\nfor x in dict_12.values():\n print(x) # Zaza 49 sport fireman\n\n# Loop through both keys and values, by using the items() method:\nfor x, y in dict_12.items():\n print(x, y)\n# name Zaza\n# age 49\n# hobby sport\n# job fireman\n\n# Copy Dictionaries\n# You cannot copy a dictionary simply by typing dict2 = dict1, \n# because: dict2 will only be a reference to dict1, and changes made in dict1 will a\n# utomatically also be made in dict2.\n\n# There are ways to make a copy, one way is to use the built-in Dictionary method copy().\ndict_13 = dict_12.copy()\nprint('dict_13: ', dict_13);\n\n# Make a copy of a dictionary with the dict() function:\ndict_14 = dict(dict_8)\nprint('dict_14: ', dict_14);\n\n# Nested Dictionaries\n# A dictionary can contain dictionaries, this is called nested dictionaries.\n\n# Create a dictionary that contain three dictionaries:\nfamily_1 = {\n \"child1\" : {\n \"name\" : \"Emil\",\n \"year\" : 2004\n },\n \"child2\" : {\n \"name\" : \"Tobias\",\n \"year\" : 2007\n },\n \"child3\" : {\n \"name\" : \"Linus\",\n \"year\" : 2011\n }\n}\nprint('family_1: ', family_1);\n\n# Or, if you want to add three dictionaries into a new dictionary:\n# Create three dictionaries, then create one dictionary that will contain the other three dictionaries:\n\nchild1 = {\n \"name\" : \"Emil\",\n \"year\" : 2004\n}\nchild2 = {\n \"name\" : \"Tobias\",\n \"year\" : 2007\n}\nchild3 = {\n \"name\" : \"Linus\",\n \"year\" : 2011\n}\n\nfamily_2 = {\n \"child1\" : child1,\n \"child2\" : child2,\n \"child3\" : child3\n}\nprint('family_2: ', family_2) # {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}\n\n# Access Items in Nested Dictionaries\n# To access items from a nested dictionary, you use the name of the dictionaries, \n# starting with the outer dictionary:\nprint(family_2[\"child2\"][\"name\"]) # Tobias\n\n# Dictionary Methods\n# Python has a set of built-in methods that you can use on dictionaries.\n\n# clear()\tRemoves all the elements from the dictionary\n# copy()\tReturns a copy of the dictionary\n# get()\tReturns the value of the specified key\n# items()\tReturns a list containing a tuple for each key value pair\n# keys()\tReturns a list containing the dictionary's keys\n# pop()\tRemoves the element with the specified key\n# popitem()\tRemoves the last inserted key-value pair\n# setdefault()\tReturns the value of the specified key. If the key does not exist: insert the key, with the specified value\n# update()\tUpdates the dictionary with the specified key-value pairs\n# values()\tReturns a list of all the values in the dictionary\n","repo_name":"BrahimS/my_python","sub_path":"basics/dico.py","file_name":"dico.py","file_ext":"py","file_size_in_byte":8767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27442244266","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom functools import partial\n\nimport tensorflow as tf\nimport tensorflow.keras as tfk\n\nfrom dynastes import activations\nfrom dynastes.blocks import layer_factory\nfrom dynastes.layers.base_layers import DynastesBaseLayer\nfrom dynastes.ops import t2t_common\nfrom dynastes.util import cache_context\nfrom dynastes.util.layer_util import call_masked as cm\nfrom dynastes.util.layer_util import compute_mask_if_possible as compm\n\n\n# A module that only depends on `keras.layers` import these from here.\n\n@tf.keras.utils.register_keras_serializable(package='Dynastes')\nclass _AttentionBlock1D(DynastesBaseLayer):\n\n def __init__(self,\n attention_dim,\n output_dim,\n kernel_size=1,\n attention_type='Attention1D',\n q_type='Conv1D',\n k_type=None,\n v_type=None,\n out_type=None,\n skip_out=False,\n num_heads=1,\n multiquery_attention=False,\n depth_multiplier=1,\n strides=1,\n dilation_rate=1,\n grouped=False,\n group_size=1,\n padding='same',\n activation=None,\n use_bias=False,\n relative=False,\n local=False,\n sparse=False,\n masked=False,\n dropout_rate=0.,\n max_relative_position=2,\n lsh_bucket_length=4,\n block_length=4,\n filter_width=2,\n mask_right=False,\n add_relative_to_values=False,\n scaled=False,\n return_attn_weights=False,\n cache_kv=False,\n separable_prepointwise=False,\n separable_prepointwise_depth='min',\n **kwargs):\n kwargs['supports_caching'] = True\n super(_AttentionBlock1D, self).__init__(**kwargs)\n self.q_type = q_type\n self.activation = activations.get(activation)\n self.use_bias = use_bias\n\n if k_type is None:\n self.k_type = q_type\n else:\n self.k_type = k_type\n\n if v_type is None:\n self.v_type = q_type\n else:\n self.v_type = v_type\n\n if out_type is None:\n self.out_type = q_type\n else:\n self.out_type = out_type\n\n self.attention_dim = attention_dim\n self.output_dim = output_dim\n self.kernel_size = kernel_size\n self.num_heads = num_heads\n self.strides = strides\n self.dilation_rate = dilation_rate\n self.depth_multiplier = depth_multiplier\n self.padding = padding\n self.grouped = grouped\n self.group_size = group_size\n self.multiquery_attention = multiquery_attention\n self.relative = relative\n self.local = local\n self.masked = masked\n self.sparse = sparse\n self.dropout_rate = dropout_rate\n self.max_relative_position = max_relative_position\n self.lsh_bucket_length = lsh_bucket_length\n self.block_length = block_length\n self.filter_width = filter_width\n self.mask_right = mask_right\n self.add_relative_to_values = add_relative_to_values\n self.return_attn_weights = return_attn_weights\n self.supports_masking = True\n self.cache_kv = cache_kv\n self.scaled = scaled\n self.separable_prepointwise = separable_prepointwise\n self.separable_prepointwise_depth = separable_prepointwise_depth\n self.skip_out = skip_out\n\n conv_partial = partial(layer_factory.get_1d_layer, kernel_size=kernel_size,\n grouped=grouped,\n group_size=group_size,\n depth_multiplier=depth_multiplier,\n padding=padding,\n activation=activation,\n use_bias=use_bias,\n bias_initializer=self.get_initializer('bias'),\n kernel_regularizer=self.get_regularizer('kernel'),\n bias_regularizer=self.get_regularizer('bias'),\n activity_regularizer=None,\n kernel_constraint=self.get_constraint('kernel'),\n bias_constraint=self.get_constraint('bias'),\n separable_prepointwise=separable_prepointwise,\n separable_prepointwise_depth=separable_prepointwise_depth)\n q_filters = attention_dim\n k_filters = attention_dim\n if skip_out:\n v_filters = output_dim\n else:\n v_filters = attention_dim\n\n if multiquery_attention:\n k_filters //= num_heads\n v_filters //= num_heads\n self.k_filters = k_filters\n self.v_filters = v_filters\n\n q_strides = strides\n kv_strides = strides\n kv_dilation_rate = dilation_rate\n attn_strides = 1\n attn_dilation_rate = 1\n if attention_type in ['LocalizedAttentionLayer1D'] and strides != 1:\n kv_strides = 1\n attn_strides = strides\n attn_dilation_rate = dilation_rate\n\n init_stddev = output_dim ** -0.5\n\n self.q_layer = conv_partial(type=self.q_type,\n kernel_initializer=tfk.initializers.RandomNormal(\n stddev=init_stddev * (k_filters ** -0.5)),\n filters=q_filters,\n strides=q_strides,\n dilation_rate=dilation_rate, name='Conv-Q',\n wnorm=self.wnorm,\n wlrmul=self.lrmul,\n wgain=self.gain,\n use_wscale=self.use_wscale)\n self.k_layer = conv_partial(type=self.k_type,\n kernel_initializer=tfk.initializers.RandomNormal(stddev=init_stddev),\n filters=k_filters,\n strides=kv_strides,\n dilation_rate=kv_dilation_rate, name='Conv-K',\n wnorm=self.wnorm,\n wlrmul=self.lrmul,\n wgain=self.gain,\n use_wscale=self.use_wscale)\n self.v_layer = conv_partial(type=self.v_type,\n kernel_initializer=tfk.initializers.RandomNormal(stddev=init_stddev),\n filters=v_filters,\n strides=kv_strides,\n dilation_rate=kv_dilation_rate, name='Conv-V',\n wnorm=self.wnorm,\n wlrmul=self.lrmul,\n wgain=self.gain,\n use_wscale=self.use_wscale)\n\n if self.skip_out:\n self.out_layer = None\n else:\n self.out_layer = conv_partial(type=self.out_type,\n kernel_initializer=tfk.initializers.RandomNormal(\n stddev=init_stddev * (output_dim ** -0.5)),\n filters=output_dim,\n strides=1,\n dilation_rate=1, name='Conv-Out',\n wnorm=self.wnorm,\n wlrmul=self.lrmul,\n wgain=self.gain,\n use_wscale=self.use_wscale)\n\n attention_padding = padding\n self.attention_layer = layer_factory.get_1D_attention_layer(\n type=attention_type,\n strides=attn_strides,\n dilation_rate=attn_dilation_rate,\n num_heads=num_heads,\n padding=attention_padding,\n multiquery_attention=multiquery_attention,\n preshaped_q=True,\n relative=relative,\n local=local,\n masked=masked,\n sparse=sparse,\n dropout_rate=dropout_rate,\n max_relative_position=max_relative_position,\n lsh_bucket_length=lsh_bucket_length,\n block_length=block_length,\n mask_right=mask_right,\n filter_width=filter_width,\n add_relative_to_values=add_relative_to_values,\n scaled=scaled,\n )\n\n def compute_mask(self, inputs, mask=None):\n if mask is not None:\n q_mask = compm(self.q_layer, inputs, mask=mask)\n return q_mask\n return mask\n\n def get_config(self):\n config = {\n 'q_type': self.q_type,\n 'k_type': self.k_type,\n 'v_type': self.v_type,\n 'out_type': self.out_type,\n 'skip_out': self.skip_out,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'multiquery_attention': self.multiquery_attention,\n 'attention_dim': self.attention_dim,\n 'output_dim': self.output_dim,\n 'depth_multiplier': self.depth_multiplier,\n 'kernel_size': self.kernel_size,\n 'num_heads': self.num_heads,\n 'strides': self.strides,\n 'dilation_rate': self.dilation_rate,\n 'padding': self.padding,\n 'grouped': self.grouped,\n 'group_size': self.group_size,\n 'relative': self.relative,\n 'local': self.local,\n 'masked': self.masked,\n 'sparse': self.sparse,\n 'dropout_rate': self.dropout_rate,\n 'max_relative_position': self.max_relative_position,\n 'lsh_bucket_length': self.lsh_bucket_length,\n 'block_length': self.block_length,\n 'filter_width': self.filter_width,\n 'mask_right': self.mask_right,\n 'add_relative_to_values': self.add_relative_to_values,\n 'cache_kv': self.cache_kv,\n 'scaled': self.scaled,\n 'separable_prepointwise': self.separable_prepointwise,\n 'separable_prepointwise_depth': self.separable_prepointwise_depth,\n }\n base_config = super(_AttentionBlock1D, self).get_config()\n return {**base_config, **config}\n\n def compute_output_shape(self, input_shape):\n qs = self.q_layer.compute_output_shape(input_shape)\n ks = self.k_layer.compute_output_shape(input_shape)\n vs = self.v_layer.compute_output_shape(input_shape)\n output_shape = self.attention_layer.compute_output_shape([qs, ks, vs])\n output_shape, attn_weights_shape = output_shape\n if not self.skip_out:\n output_shape = self.out_layer.compute_output_shape(output_shape)\n if self.return_attn_weights:\n return [output_shape, attn_weights_shape]\n return output_shape\n\n\n@tf.keras.utils.register_keras_serializable(package='Dynastes')\nclass AttentionBlock1D(_AttentionBlock1D):\n\n def request_cache(self, batch_size=1, max_length=1):\n return {\n }\n\n def compute_mask(self, inputs, mask=None):\n if mask is not None:\n q_mask = compm(self.q_layer, inputs[0], mask=mask[0])\n return q_mask\n return mask\n\n def call(self, inputs, training=None, mask=None, cache=None, decode_loop_step=None):\n qx, sx = inputs\n if mask is not None:\n qmask, smask = mask\n else:\n qmask, smask = (None, None)\n q, q_mask = cm(self.q_layer, qx, training=training, mask=qmask)\n\n # In cross-attention we may compute KV once and perform attention on it in subsequent steps\n\n def get_kv():\n def do_get_kv():\n k, k_mask = cm(self.k_layer, sx, training=training, mask=smask)\n v, v_mask = cm(self.v_layer, sx, training=training, mask=smask)\n return k, k_mask, v, v_mask\n\n if self.cache_kv and cache_context.cache_context is not None:\n with cache_context.SubContext(self.name):\n if 'cached_kv' in cache_context.cache:\n k, k_mask, v, v_mask = cache_context.cache['cached_kv']\n else:\n k, k_mask, v, v_mask = do_get_kv()\n cache_context.cache['cached_kv'] = k, k_mask, v, v_mask\n else:\n k, k_mask, v, v_mask = do_get_kv()\n return k, k_mask, v, v_mask\n\n if cache is not None:\n if 'k' not in cache:\n k, k_mask, v, v_mask = get_kv()\n\n # Update cache\n cache[\"k\"] = k\n cache[\"v\"] = v\n if mask is not None:\n cache[\"k_mask\"] = k_mask\n cache[\"v_mask\"] = v_mask\n else:\n k = cache[\"k\"]\n v = cache[\"v\"]\n if mask is not None:\n k_mask = cache[\"k_mask\"]\n v_mask = cache[\"v_mask\"]\n else:\n k, k_mask, v, v_mask = get_kv()\n if mask is not None:\n mask = [q_mask, tf.logical_and(k_mask, v_mask)]\n x, weights = self.attention_layer([q, k, v], mask=mask, training=training)\n if not self.skip_out:\n x = self.out_layer(x, mask=mask, training=training)\n if self.return_attn_weights:\n return x, weights\n return x\n\n\n@tf.keras.utils.register_keras_serializable(package='Dynastes')\nclass SelfAttentionBlock1D(AttentionBlock1D):\n\n def request_cache(self, batch_size=1, max_length=1):\n return {\n 'k': tf.zeros((batch_size, max_length, self.k_filters)),\n 'v': tf.zeros((batch_size, max_length, self.v_filters)),\n 'k_mask': tf.cast(tf.zeros((batch_size, max_length)), tf.bool),\n 'v_mask': tf.cast(tf.zeros((batch_size, max_length)), tf.bool)\n }\n\n def compute_mask(self, inputs, mask=None):\n if mask is not None:\n q_mask = compm(self.q_layer, inputs, mask=mask)\n return q_mask\n return mask\n\n def call(self, inputs, training=None, mask=None, cache=None, decode_loop_step=None, pad_q_to_kv=False):\n x = inputs\n q, q_mask = cm(self.q_layer, x, training=training, mask=mask)\n k, k_mask = cm(self.k_layer, x, training=training, mask=mask)\n v, v_mask = cm(self.v_layer, x, training=training, mask=mask)\n if cache is not None:\n # Combine cached keys and values with new keys and values.\n if cache[\"k\"] is not None:\n # Update cache\n if decode_loop_step is not None:\n\n cache_k_shape = cache[\"k\"].shape.as_list()\n indices = tf.reshape(\n tf.one_hot(decode_loop_step, cache_k_shape[1], dtype=k.dtype),\n [1, cache_k_shape[1], 1])\n k = cache[\"k\"] + k * indices\n if mask is not None:\n indices = tf.reshape(\n tf.one_hot(decode_loop_step, cache_k_shape[1], dtype=tf.float16),\n [1, cache_k_shape[1]])\n k_mask = tf.logical_or(cache[\"k_mask\"], (tf.cast(k_mask, tf.float16) * indices) > 0.)\n\n cache_v_shape = cache[\"v\"].shape.as_list()\n indices = tf.reshape(\n tf.one_hot(decode_loop_step, cache_v_shape[1], dtype=v.dtype),\n [1, cache_v_shape[1], 1])\n v = cache[\"v\"] + v * indices\n if mask is not None:\n indices = tf.reshape(\n tf.one_hot(decode_loop_step, cache_v_shape[1], dtype=tf.float16),\n [1, cache_v_shape[1]])\n v_mask = tf.logical_or(cache[\"v_mask\"], (tf.cast(v_mask, tf.float16) * indices) > 0.)\n else:\n k = tf.concat([tf.cast(cache[\"k\"], k.dtype), k], axis=1)\n v = tf.concat([tf.cast(cache[\"v\"], v.dtype), v], axis=1)\n if mask is not None:\n k_mask = tf.concat([tf.cast(cache[\"k_mask\"], k_mask.dtype), k_mask], axis=1)\n v_mask = tf.concat([tf.cast(cache[\"v_mask\"], v_mask.dtype), v_mask], axis=1)\n\n # Update cache\n cache[\"k\"] = k\n cache[\"v\"] = v\n if mask is not None:\n cache[\"k_mask\"] = k_mask\n cache[\"v_mask\"] = v_mask\n\n q_shape = t2t_common.shape_list(q)\n kv_shape = t2t_common.shape_list(k)\n\n if pad_q_to_kv:\n if q_shape[1] != kv_shape[1]:\n if decode_loop_step is not None:\n q_prepad = decode_loop_step\n q_postpad = (kv_shape[1] - q_shape[1]) - decode_loop_step\n\n else:\n q_prepad = (kv_shape[1] - q_shape[1])\n q_postpad = 0\n q = tf.pad(q, paddings=[[0, 0], [q_prepad, q_postpad], [0, 0]])\n if mask is not None:\n q_mask = tf.pad(q_mask, paddings=[[0, 0], [q_prepad, q_postpad]])\n else:\n # This is just stupid autograph nonsense, ignore it\n if decode_loop_step is not None:\n q_prepad = decode_loop_step\n else:\n q_prepad = (kv_shape[1] - q_shape[1])\n else:\n # This is just stupid autograph nonsense, ignore it\n if decode_loop_step is not None:\n q_prepad = decode_loop_step\n else:\n q_prepad = (kv_shape[1] - q_shape[1])\n\n if mask is not None:\n mask = [q_mask, tf.logical_and(k_mask, v_mask)]\n x, weights = self.attention_layer([q, k, v], mask=mask, training=training)\n if not self.skip_out:\n x = self.out_layer(x, mask=mask, training=training)\n x_shape = t2t_common.shape_list(x)\n if pad_q_to_kv:\n if q_shape[1] != kv_shape[1]:\n if decode_loop_step is not None:\n x = tf.slice(x, [0, q_prepad, 0], [x_shape[0], 1, x_shape[2]])\n else:\n x = tf.slice(x, [0, q_prepad, 0], [x_shape[0], q_shape[1], x_shape[2]])\n if self.return_attn_weights:\n return x, weights\n return x\n","repo_name":"dynastes-team/dynastes","sub_path":"dynastes/blocks/attention_blocks.py","file_name":"attention_blocks.py","file_ext":"py","file_size_in_byte":18870,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"85"} +{"seq_id":"35932056433","text":"import os\nimport glob\nimport sys\nimport time\nfrom comet_ml import Experiment, OfflineExperiment\nfrom argparse import Namespace\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_a_logger(args):\n file_handler = logging.FileHandler(args.stats_file)\n stream_handler = logging.StreamHandler(sys.stdout)\n logging.basicConfig(\n handlers=[file_handler, stream_handler],\n format=\"%(asctime)s:%(levelname)s: %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n level=logging.INFO,\n )\n logger = logging.getLogger()\n return logger\n\n\ndef launch_comet_experiment(args):\n \"\"\"Launch a new named Comet.ml experiment, logging parameters along the way.\"\"\"\n if args.offline_experiment:\n experiment = OfflineExperiment(\n project_name=\"lidar_pac\",\n offline_directory=os.path.join(args.path, \"experiments/\"),\n auto_log_co2=False,\n )\n else:\n experiment = Experiment(\n project_name=\"lidar_pac\",\n auto_log_co2=False,\n disabled=args.disabled,\n )\n experiment.log_parameters(vars(args))\n if args.comet_name:\n experiment.add_tags([args.mode])\n experiment.set_name(args.comet_name)\n else:\n experiment.add_tag(args.mode)\n args.experiment = experiment\n return experiment\n\n\ndef setup_experiment_folder(args, task=\"learning\"):\n\n results_path = os.path.join(args.path, f\"experiments/\")\n results_path = os.path.join(results_path, f\"{task}/{args.mode}\")\n args.results_path = results_path\n\n current_time = time.time()\n run_name = str(time.strftime(\"%Y-%m-%d_%Hh%Mm%Ss\"))\n\n args.stats_path = os.path.join(results_path, run_name) + \"/\"\n create_dir(args.stats_path)\n logger.info(f\"Results folder is {args.stats_path}\")\n\n args.stats_file = os.path.join(args.stats_path, \"stats.txt\")\n\n\ndef update_namespace_with_another_namespace(args, args_local):\n \"\"\"Update first Namespace with args of second Namespace. This creates a novel object.\"\"\"\n\n args_dict = vars(args).copy()\n args_local_dict = vars(args_local).copy()\n\n args_dict.update(args_local_dict)\n updated_args = Namespace(**args_dict)\n\n return updated_args\n\n\ndef create_dir(dir_name):\n \"\"\"Create a new folder if does not exists\"\"\"\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n\ndef get_files_of_type_in_folder(folder_path, extension):\n \"\"\"Get a list of all files in folder, with a specific particular extension.\n Folder path is a string path, and extension is something like: '.las', '.tif', etc.\"\"\"\n filenames = os.listdir(folder_path)\n filenames = [\n os.path.join(folder_path, l) for l in filenames if l.lower().endswith(extension)\n ]\n return filenames\n\n\ndef fast_scandir(dirname):\n \"\"\"List all subfolders (abs paths). See https://stackoverflow.com/a/40347279/8086033\"\"\"\n subfolders = [f.path for f in os.scandir(dirname) if f.is_dir()]\n for dirname in list(subfolders):\n subfolders.extend(fast_scandir(dirname))\n return subfolders\n\n\ndef get_subfolder_in_folder_by_name(path, subfolder_name):\n \"\"\"Find the path to a subfolder in path, whose name matches subfolder_name.\"\"\"\n subfolders = fast_scandir(path)\n subfolders = [\n f\n for f in subfolders\n if (subfolder_name in f) and (f.split(\"/\")[-1] == subfolder_name)\n ]\n return subfolders[0]\n\n\ndef get_filename_no_extension(filename):\n \"\"\"path/to/filename.extension -> filename\"\"\"\n basename = os.path.basename(filename)\n return os.path.splitext(basename)[0]\n\n\ndef get_unprocessed_files(input_datasets_folder, output_datasets_folder):\n \"\"\"\n Get all filenames from input_datasets_folder that have no matching file (sufix-agnostic) in output_datasets_folder.\n Ignore files in subfolders.\n \"\"\"\n unlabeled = get_all_files_in_folder(input_datasets_folder)\n labeled = get_all_files_in_folder(output_datasets_folder)\n\n unlabeled = [\n p\n for p in unlabeled\n if not any(\n get_filename_no_extension(p) == get_filename_no_extension(p_labeled)\n for p_labeled in labeled\n )\n ]\n return unlabeled\n\n\ndef get_all_files_in_folder(folder):\n \"\"\"Get filenames from folder, ignoring subfolders.\"\"\"\n files = glob.glob(os.path.join(folder, \"*\"), recursive=False)\n files = [l for l in files if os.path.isfile(l)]\n return files\n\n\n# TODO: find a more appropriate place\ndef get_trained_model_path_from_experiment(path, experiment_id):\n path_experiments = os.path.join(path, \"experiments/\")\n experiment_folder = get_subfolder_in_folder_by_name(path_experiments, experiment_id)\n models = get_files_of_type_in_folder(experiment_folder, \".pt\")\n try:\n model_path = [m for m in models if \"full\" in m][0]\n except:\n model_path = [m for m in models if \"fold_n=1\" in m][0]\n return model_path\n\n\ndef format_float_as_percentage(value):\n \"\"\"Format float value as a percentage string.\"\"\"\n return f\"{value:.0%}\"\n","repo_name":"IGNF/StrataNet2-Vegetation-Coverage-Maps","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"73161960279","text":"from sklearn.decomposition import PCA\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import load_digits\ndigits = load_digits()\ndigit_data = digits.data\nsub_data = digit_data[0:100,:]\nprint (sub_data.shape)\nfig, axe = plt.subplots(1,12,subplot_kw=dict(xticks=[], yticks=[]))\n\nfor i in range(0,12):\n axe[i].imshow(sub_data[i,:].reshape((8,8)),cmap=plt.cm.binary, interpolation='nearest')\n\nplt.show()\n\ndigit_pca = PCA(n_components=36,copy=True,whiten=False)\nnew_data = digit_pca.fit_transform(sub_data);\nprint(new_data.shape)\n\nfig, axe = plt.subplots(1,12,subplot_kw=dict(xticks=[], yticks=[]))\nfor i in range(0,12):\n axe[i].imshow(new_data[i,:].reshape((6,6)),cmap=plt.cm.binary, interpolation='nearest')\n\nplt.show()\n","repo_name":"linlinxiaostudent/DeepLearning_AE","sub_path":"PCA.py","file_name":"PCA.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18927156948","text":"# -*- coding:utf-8 -*-\n# !/usr/bin/env python\n\"\"\"\nDate: 2022/9/27 19:05\nDesc: CLI 命令文件\n\"\"\"\nfrom pathlib import Path\nfrom subprocess import run\nfrom typing import Optional\n\nimport akshare as ak\nimport typer\n\nimport aktools\n\napp = typer.Typer()\n\n\ndef version_callback(value: bool):\n if value:\n typer.echo(f\"{aktools.__title__} v{aktools.__version__}\")\n raise typer.Exit()\n\n\n@app.command()\ndef main(\n host: str = typer.Option(\"127.0.0.1\", \"--host\", \"-H\", help=\"设置主机地址\"),\n port: int = typer.Option(\n 8080, \"--port\", \"-P\", min=0, max=65535, clamp=True, help=\"设置端口\"\n ),\n auto: bool = typer.Option(False, \"--auto\", \"-A\", help=\"自动打开游览器,默认为不打开\"),\n version: Optional[bool] = typer.Option(\n None,\n \"--version\",\n \"-v\",\n help=\"查看 AKTools 的版本\",\n callback=version_callback,\n is_eager=True,\n ),\n) -> None:\n app_dir = Path(__file__).parent\n order_str = (\n f\"python -m uvicorn main:app --host {host} --port {port} --app-dir {app_dir}\"\n )\n typer.echo(\n f\"请访问:http://{host}:{port}/version 来获取最新的库版本信息,确保使用最新版本的 AKShare 和 AKTools\"\n )\n typer.echo(f\"当前的 AKTools 版本为:{aktools.__version__},AKShare 版本为:{ak.__version__}\")\n typer.echo(f\"点击打开 HTTP API 主页:http://{host}:{port}/\")\n typer.echo(f\"点击打开接口导览:http://{host}:{port}/docs\")\n if auto:\n typer.launch(f\"http://{host}:{port}/\")\n run(order_str, shell=True)\n\n\nif __name__ == \"__main__\":\n typer.run(main)\n","repo_name":"akfamily/aktools","sub_path":"aktools/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"zh","doc_type":"code","stars":325,"dataset":"github-code","pt":"85"} +{"seq_id":"13633484523","text":"import html\nimport re\nfrom typing import List\n\nfrom telegram import Bot, Update, ParseMode\nfrom telegram.error import BadRequest\nfrom telegram.ext import CommandHandler, MessageHandler, Filters, run_async\n\nimport tg_bot.modules.sql.blacklist_sql as sql\nfrom tg_bot import dispatcher, LOGGER\nfrom tg_bot.modules.disable import DisableAbleCommandHandler\nfrom tg_bot.modules.helper_funcs.chat_status import user_admin, user_not_admin, connection_status\nfrom tg_bot.modules.helper_funcs.extraction import extract_text\nfrom tg_bot.modules.helper_funcs.misc import split_message\n\nBLACKLIST_GROUP = 11\n\n\n@run_async\n@connection_status\ndef blacklist(bot: Bot, update: Update, args: List[str]):\n msg = update.effective_message\n chat = update.effective_chat\n\n update_chat_title = chat.title\n message_chat_title = update.effective_message.chat.title\n\n if update_chat_title == message_chat_title:\n base_blacklist_string = \"Mevcut kara listeye alınmış kelimeler:\\n\"\n else:\n base_blacklist_string = f\"{update_chat_title} içindeki mevcut kara listeye alınmış kelimeler:\\n\"\n\n all_blacklisted = sql.get_chat_blacklist(chat.id)\n\n filter_list = base_blacklist_string\n\n if len(args) > 0 and args[0].lower() == 'copy':\n for trigger in all_blacklisted:\n filter_list += f\"{html.escape(trigger)}\\n\"\n else:\n for trigger in all_blacklisted:\n filter_list += f\" - {html.escape(trigger)}\\n\"\n\n split_text = split_message(filter_list)\n for text in split_text:\n if text == base_blacklist_string:\n if update_chat_title == message_chat_title:\n msg.reply_text(\"Burada kara listeye alınmış mesaj yok!\")\n else:\n msg.reply_text(f\"{update_chat_title} içinde kara listeye alınmış mesaj yok!\",\n parse_mode=ParseMode.HTML)\n return\n msg.reply_text(text, parse_mode=ParseMode.HTML)\n\n\n@run_async\n@connection_status\n@user_admin\ndef add_blacklist(bot: Bot, update: Update):\n msg = update.effective_message\n chat = update.effective_chat\n words = msg.text.split(None, 1)\n\n if len(words) > 1:\n text = words[1]\n to_blacklist = list(set(trigger.strip() for trigger in text.split(\"\\n\") if trigger.strip()))\n\n for trigger in to_blacklist:\n sql.add_to_blacklist(chat.id, trigger.lower())\n\n if len(to_blacklist) == 1:\n msg.reply_text(f\"Kara listeye {html.escape(to_blacklist[0])} eklendi!\",\n parse_mode=ParseMode.HTML)\n\n else:\n msg.reply_text(f\"Kara listeye {len(to_blacklist)} tetikleyicileri eklendi.\",\n parse_mode=ParseMode.HTML)\n\n else:\n msg.reply_text(\"Kara listeden hangi kelimeleri çıkarmak istediÄŸini söyle.\")\n\n\n@run_async\n@connection_status\n@user_admin\ndef unblacklist(bot: Bot, update: Update):\n msg = update.effective_message\n chat = update.effective_chat\n words = msg.text.split(None, 1)\n\n if len(words) > 1:\n text = words[1]\n to_unblacklist = list(set(trigger.strip() for trigger in text.split(\"\\n\") if trigger.strip()))\n successful = 0\n\n for trigger in to_unblacklist:\n success = sql.rm_from_blacklist(chat.id, trigger.lower())\n if success:\n successful += 1\n\n if len(to_unblacklist) == 1:\n if successful:\n msg.reply_text(f\"Kara listeden {html.escape(to_unblacklist[0])} kaldırıldı!\",\n parse_mode=ParseMode.HTML)\n else:\n msg.reply_text(\"Bu kara listeye alınmış bir tetikleyici deÄŸil...!\")\n\n elif successful == len(to_unblacklist):\n msg.reply_text(f\"Kara listeden {successful} tetikleyicileri kaldırıldı.\", parse_mode=ParseMode.HTML)\n\n elif not successful:\n msg.reply_text(\"Bu tetikleyicilerin hiçbiri mevcut olmadığından kaldırılmadı.\", parse_mode=ParseMode.HTML)\n\n else:\n msg.reply_text(f\"Kara listeden {successful} tetikleyicileri kaldırıldı.\"\n f\" {len(to_unblacklist) - successful} mevcut deÄŸildi, dolayısıyla kaldırılmadı.\",\n parse_mode=ParseMode.HTML)\n else:\n msg.reply_text(\"Kara listeden hangi kelimeleri çıkarmak istediÄŸini söyle.\")\n\n\n@run_async\n@connection_status\n@user_not_admin\ndef del_blacklist(bot: Bot, update: Update):\n chat = update.effective_chat\n message = update.effective_message\n to_match = extract_text(message)\n\n if not to_match:\n return\n\n chat_filters = sql.get_chat_blacklist(chat.id)\n for trigger in chat_filters:\n pattern = r\"( |^|[^\\w])\" + re.escape(trigger) + r\"( |$|[^\\w])\"\n if re.search(pattern, to_match, flags=re.IGNORECASE):\n try:\n message.delete()\n except BadRequest as excp:\n if excp.message == \"Silinecek mesaj bulunamadı\":\n pass\n else:\n LOGGER.exception(\"Kara liste mesajı silinirken hata oluÅŸtu.\")\n break\n\n\ndef __migrate__(old_chat_id, new_chat_id):\n sql.migrate_chat(old_chat_id, new_chat_id)\n\n\ndef __chat_settings__(chat_id, user_id):\n blacklisted = sql.num_blacklist_chat_filters(chat_id)\n return \"{} kara listeye alınmış kelime var.\".format(blacklisted)\n\n\ndef __stats__():\n return \"{} sohbetlerde {} kara liste tetiklenir.\".format(sql.num_blacklist_filters(),\n sql.num_blacklist_filter_chats())\n\n\n__help__ = \"\"\"\nKara listeler, belirli tetikleyicilerin bir grupta söylenmesini engellemek için kullanılır. Tetikleyiciden bahsedildiÄŸinde, \\ mesaj hemen silinecektir. Bazen bunu uyarı filtreleriyle eÅŸleÅŸtirmek iyi bir kombinasyondur! \n\n\n*NOT:* kara listeler grup yöneticilerini etkilemez. \n\n- /kara liste: Mevcut kara listeye alınmış kelimeleri görüntüleyin. \n\n*Yalnızca yönetici:*\n\n - /addblacklist : Kara listeye bir tetikleyici ekleyin. Her satır bir tetikleyici olarak kabul edilir, bu nedenle farklı \\ satırları, birden çok tetikleyici eklemenize izin verir. \n- /unblacklist : Tetikleyicileri kara listeden kaldırın. Aynı satırsonu mantığı burada da geçerlidir, böylece \\'yi kaldırabilirsiniz. aynı anda birden fazla tetikleyici. \n- /rmblacklist : Yukarıdakiyle aynı. \n\"\"\"\n\nBLACKLIST_HANDLER = DisableAbleCommandHandler(\"blacklist\", blacklist, pass_args=True, admin_ok=True)\nADD_BLACKLIST_HANDLER = CommandHandler(\"addblacklist\", add_blacklist)\nUNBLACKLIST_HANDLER = CommandHandler([\"unblacklist\", \"rmblacklist\"], unblacklist)\nBLACKLIST_DEL_HANDLER = MessageHandler((Filters.text | Filters.command | Filters.sticker | Filters.photo) & Filters.group, del_blacklist, edited_updates=True)\ndispatcher.add_handler(BLACKLIST_HANDLER)\ndispatcher.add_handler(ADD_BLACKLIST_HANDLER)\ndispatcher.add_handler(UNBLACKLIST_HANDLER)\ndispatcher.add_handler(BLACKLIST_DEL_HANDLER, group=BLACKLIST_GROUP)\n\n__mod_name__ = \"WORD BLACKLIST🖤\"\n__handlers__ = [BLACKLIST_HANDLER, ADD_BLACKLIST_HANDLER, UNBLACKLIST_HANDLER, (BLACKLIST_DEL_HANDLER, BLACKLIST_GROUP)]\n","repo_name":"0-Atalay/LUNA-ROBOT","sub_path":"tg_bot/modules/blacklist.py","file_name":"blacklist.py","file_ext":"py","file_size_in_byte":7345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"126200878","text":"from flask import Flask, render_template, url_for, request,redirect\nfrom spotify_routes import spotify_routes\nimport requests \n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef home():\n return render_template(\"home.html\")\n\n\napp.register_blueprint(spotify_routes)\n\n \n \nif __name__ == '__main__':\n # Bind to PORT if defined, otherwise default to 5000.\n app.run(host='0.0.0.0',debug=True)","repo_name":"soph-jje/mussy","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21347831377","text":"# sorting the list in ascending orer\r\nlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\nn = []\r\n\r\nwhile list:\r\n min = list[0] \r\n for x in list: \r\n if x > min:\r\n min = x\r\n n.append(min)\r\n list.remove(min) \r\n\r\nprint(n)","repo_name":"McLeaord/100-Days-Of-Code","sub_path":"Day7/asceding.py","file_name":"asceding.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22596319559","text":"import pygame\nimport sys\nfrom interplanetary_invaders.scripts.retro_text import retro_text\nfrom interplanetary_invaders.scripts.confirm import confirmExit\nfrom interplanetary_invaders.scripts import screenshot\nfrom interplanetary_invaders.scripts.sound import Sound\nfrom interplanetary_invaders.scripts.utils import fix_path, clamp\nfrom interplanetary_invaders.scripts.transition import black_out, fade_in\nfrom interplanetary_invaders.scripts import joystick\n\npygame.init()\n\nclock = pygame.time.Clock()\n\nclass LoseWin:\n def __init__(self, display, images, money = [1, 1, 1, 1, [], 0, 0], mode = \"won\"):\n self.display = display\n self.images = images\n self.mode = mode\n self.frame = 1\n self.frame_time = 0\n self.frame_rate = 1 / 25\n self.time_passed = 0\n self.anim_done = False\n self.done = False\n self.text = [\"Retry\", \"Return to Map\", \"Exit Game\"]\n if mode == \"won\":\n self.text = self.text[1:]\n self.options_range = (0, len(self.text) - 1)\n self.selected_option = 0\n self.money_old, self.money_new, self.bonus, self.bonus1, self.acc, self.lost, self.maxcombo = money\n try:\n self.acc_per = self.acc.count(True) / len(self.acc)\n self.acc_per2 = round(self.acc_per * 100, 3)\n except ZeroDivisionError:\n self.acc_per = 0\n self.acc_per2 = 0\n self.money_new += round(self.bonus)\n self.money_new += round(self.bonus1 * self.acc_per)\n self.money_sound = Sound(fix_path(\"audio/money.wav\"))\n self.register_sound = Sound(fix_path(\"audio/cashRegister.wav\"))\n if mode == \"won\":\n self.money_sound.play(-1)\n self.exit = False\n self.retry = False\n self.stopped = False\n\n def main(self):\n self.draw()\n fade_in(self.display, 3)\n while not self.done:\n self.events()\n self.draw()\n self.update()\n if not (self.retry or self.exit):\n black_out(self.display, 3)\n return self.retry, self.exit\n\n def events(self):\n for event in pygame.event.get():\n joystick.Update(event)\n if not hasattr(event, \"key\"):\n event.key = None\n if event.type == pygame.KEYUP or joystick.WasEvent():\n if event.key == pygame.K_F2 or joystick.JustPressedLB():\n screenshot.capture(\"WL\", self.display)\n if event.key == pygame.K_ESCAPE or joystick.BackEvent():\n self.money_old = self.money_new\n if event.key == pygame.K_TAB:\n self.selected_option += 1\n if self.selected_option > self.options_range[1]:\n self.selected_option = self.options_range[0]\n if event.key == pygame.K_UP or joystick.JustWentUp():\n self.selected_option = clamp(self.selected_option - 1, *self.options_range)\n if event.key == pygame.K_DOWN or joystick.JustWentDown():\n self.selected_option = clamp(self.selected_option + 1, *self.options_range)\n if event.key == pygame.K_y or joystick.JustPressedY():\n self.info()\n if event.key == pygame.K_RETURN or joystick.JustPressedA():\n self.stopped = True\n self.done = True\n if self.mode == \"won\":\n self.register_sound.play()\n self.money_sound.stop()\n text = self.text[self.selected_option]\n if text == \"Retry\":\n self.retry = True\n if text == \"Exit Game\":\n self.exit = True\n\n def info(self):\n display = self.display.copy()\n done = False\n rect = pygame.Rect(0, 0, 600, 400)\n rect.center = self.display.get_rect().center\n data = f\"\"\"\nShots fired: {len(self.acc)}\nShots hit: {self.acc.count(True)}\nShots missed: {self.acc.count(False)}\nAccuracy: {self.acc_per2}%\n\nTotal attempts to beat this level:{self.lost}\n\nMax Combo: {self.maxcombo}\"\"\"\n while not done:\n for event in pygame.event.get():\n joystick.Update(event)\n if not hasattr(event, \"key\"):\n event.key = None\n if event.type == pygame.QUIT:\n done = True\n if event.type == pygame.KEYUP or joystick.WasEvent():\n if event.key == pygame.K_F2 or joystick.JustPressedLB():\n screenshot.capture(\"WL_info\", self.display)\n if event.key in (pygame.K_q, pygame.K_ESCAPE, pygame.K_RETURN, pygame.K_SPACE, pygame.K_y) or joystick.BackEvent() or joystick.GoEvent():\n done = True\n self.display.blit(display, (0, 0))\n pygame.draw.rect(self.display, (40, 40, 40), rect)\n pygame.draw.rect(self.display, (255, 255, 0), rect, 1)\n for index, line in enumerate(data.split(\"\\n\")):\n retro_text((121, 142 + index * 14), self.display, 14, line, color=(0, 0, 0))\n retro_text((120, 140 + index * 14), self.display, 14, line)\n pygame.display.update()\n joystick.Reset()\n\n def draw(self):\n self.display.blit(self.images[\"background\"], (0, 0))\n rect = pygame.Rect(0, 0, 400, 200)\n rect.center = self.display.get_rect().center\n self.display.blit(pygame.transform.scale(self.images[f\"you_{self.mode}{self.frame}\"], (400, 200)), rect)\n rect.move_ip(50, 0)\n for e, text in enumerate(self.text):\n color = (255, 255, 255)\n if e == self.selected_option:\n color = (255, 255, 175)\n retro_text(rect.move(0, 20 * e).bottomleft, self.display, 14, text, anchor=\"topleft\", color=color)\n self.display.blit(self.images[\"bullet\"], (rect.left - 20, rect.bottom + 20 * self.selected_option))\n if self.mode == \"won\":\n retro_text((400, 25), self.display, 14, \"Loot:\", anchor=\"center\")\n retro_text((400, 50), self.display, 14, round(self.money_old), anchor=\"center\")\n retro_text((400, 75), self.display, 14, \"Fast Victory Bonus\", anchor=\"center\")\n retro_text((400, 100), self.display, 14, round(self.bonus), anchor=\"center\")\n retro_text((400, 125), self.display, 14, \"Accuracy Bonus\", anchor=\"center\")\n retro_text((400, 150), self.display, 14, round(self.bonus1 * self.acc_per), anchor=\"center\")\n retro_text((400, 165), self.display, 14, \"Press Y for more info\", anchor=\"center\")\n\n def update(self):\n self.frame_time += self.time_passed\n if self.frame_time >= self.frame_rate and not self.anim_done:\n self.frame += 1\n self.frame_time = 0\n if self.frame > 50 and self.mode == \"won\":\n self.frame = 50\n self.anim_done = True\n if self.frame > 50 and self.mode == \"lost\":\n self.frame = 1\n if self.mode == \"won\":\n self.money_old -= (self.money_old - self.money_new) / 25\n if round(self.money_old) == round(self.money_new) and not self.stopped and self.mode == \"won\":\n self.money_sound.stop()\n self.register_sound.play()\n self.stopped = True\n pygame.display.update()\n self.time_passed = clock.tick(60) / 1000\n","repo_name":"nachomonkey/Interplanetary-Invaders","sub_path":"interplanetary_invaders/scripts/lose_win.py","file_name":"lose_win.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"85"} +{"seq_id":"30461774722","text":"\r\n# TIPOS NUMERICOS\r\n# int -> numeros inteiros\r\n# float -> numeros reais\r\n# bool -> 0 ou 1\r\n# str -> string\r\n\r\n#num1 = float(input())\r\n#num2 = float(input())\r\n#num3 = float(input())\r\n\r\n#media = (num1* 2+num2*3+num3*5)/10\r\n#print(\"MEDIA = %1.1f\" % media)\r\n\r\n\r\nlinha = input()\r\na, b, c = map(float, linha.split())\r\ndelta = (b*b-4*a*c)\r\nif delta<0:\r\n print('Impossível Calcular')\r\nelif delta==0:\r\n r1 = (-b + ((b * b - 4 * a * c) ** (1 / 2))) / (2 * a)\r\n r2 = r1\r\n print('R1 = %1.5f' % r1)\r\n print('R2 = %1.5f' % r2)\r\nelse:\r\n r1 = (-b + ((b * b - 4 * a * c) ** (1 / 2))) / (2 * a)\r\n r2 = (-b - ((b * b - 4 * a * c) ** (1 / 2))) / (2 * a)\r\n print('R1 = %1.5f'%r1)\r\n print('R2 = %1.5f'%r2)\r\n\r\n","repo_name":"JoseCarlos33/Pyhton","sub_path":"Questões Resolvidas & Resumos de Assuntos/NUMEROS.py","file_name":"NUMEROS.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42230696812","text":"# https://www.youtube.com/watch?v=nuF5lCI49XM\n# https://www.youtube.com/watch?v=1epYjGrkvnE\n# https://www.youtube.com/watch?v=ctfTUC4DuxU\n# https://www.youtube.com/watch?v=Nhk8C9JNvVw\n\n# other links\n# https://www.youtube.com/watch?v=OJ8isyws2yw\n\n# 25 videos\n# https://www.youtube.com/watch?v=ve_0h4Y8nuI&list=PLhTjy8cBISEqkN-5Ku_kXG4QW33sxQo0t\n\n# scrapy cralw ofertacasas -o OfCa_items.json\n# scrapy genspider {nombre archivo} {URL} -> genera un new file\n# user agent\n# https://developers.whatismybrowser.com/useragents/explore/software_name/googlebot/\n# install package scrapy user agents\n\n# Sample master-detail with scrapy\n# https://towardsdatascience.com/a-minimalist-end-to-end-scrapy-tutorial-part-iii-bcd94a2e8bf3\n\nimport scrapy\nimport json\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom ..items import OfertacasasItems\nfrom ..Tools import CustomTools\n\n\nclass OfertaCasasSpider(CrawlSpider):\n name = 'ofertacasas'\n allowed_domain = ['www.vivanuncios.com.mx']\n start_url = ['https://www.vivanuncios.com.mx/s-casas-en-venta/colima-col/v1c1293l10256p1']\n\n rules = {\n Rule(LinkExtractor(allow=(), restrict_xpaths=('//a[@class=\"icon-pagination-right\"]'))),\n Rule(LinkExtractor(allow=(), restrict_xpaths=('//a[@class=\"href-link tile-title-text\"]')),\n callback='parse_item', follow=False)\n }\n\n def start_requests(self):\n urls = [\n 'https://www.vivanuncios.com.mx/s-casas-en-venta/colima-col/v1c1293l10256p1'\n ]\n\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n contenedor = response.xpath('//*[@id=\"tileRedesign\"]/div')\n\n for i in range(len(contenedor)):\n OfCa_items = OfertacasasItems()\n # OfCa_items['house_id'] = contenedor[i].xpath('//div[@class=\"tile-contact-us\"]').attrib['data-tileadid']\n OfCa_items['house_id'] = contenedor[i].xpath(\n '//div[contains(@class,\"tileV2\") and contains(@class, \"REAdTileV2\") and contains(@class,\"regular\")]')[\n i].attrib['data-tileadid']\n OfCa_items['url'] = contenedor[i].xpath('.//div[@class=\"tile-desc one-liner\"]/a/@href').get()\n OfCa_items['location'] = contenedor[i].xpath('.//div[@class=\"tile-location one-liner\"]/b').get()\n OfCa_items['description'] = contenedor[i].xpath('.//div[@class=\"expanded-description\"]/text()').get()\n OfCa_items['bedrooms'] = contenedor[i].xpath(\n './/div[@class=\"chiplets-inline-block re-bedroom\"]/text()').get()\n OfCa_items['baths'] = contenedor[i].xpath('.//div[@class=\"chiplets-inline-block re-bathroom\"]/text()').get()\n OfCa_items['area'] = contenedor[i].xpath('.//div[@class=\"chiplets-inline-block surface-area\"]/text()').get()\n OfCa_items['price'] = contenedor[i].xpath('.//span[@class=\"ad-price\"]/text()').get()\n\n garage = contenedor[i].xpath('.//div[contains(@class,\"car-parking\")]/text()').get()\n OfCa_items['garage'] = 0\n if garage is not None:\n OfCa_items['garage'] = garage\n\n parametros = {\"OfCa_items\": OfCa_items}\n url_images = \"https://www.vivanuncios.com.mx\" + OfCa_items['url']\n yield scrapy.Request(url=url_images, callback=self.parse_images, cb_kwargs=parametros)\n\n def parse_images(self, response, OfCa_items):\n json_contenedor = response.xpath('//script[@type=\"application/ld+json\"]').get()\n json_contenedor = CustomTools.CleanHtml(json_contenedor)\n jContend = json.loads(json_contenedor)\n OfCa_items['latitude'] = jContend[0]['geo']['latitude']\n OfCa_items['longitude'] = jContend[0]['geo']['longitude']\n OfCa_items['url'] = response.url\n\n img_items = []\n selectorImages = response.xpath('//div[@class=\"gallery-slide\"]/div/div/picture')\n for i in range(1, len(selectorImages)):\n img = selectorImages.xpath('.//source[@type=\"image/jpeg\"]')[i].attrib['data-srcset']\n img_items.append(img)\n\n OfCa_items['images'] = img_items\n yield OfCa_items\n","repo_name":"MaCoAr/OfertaCasas","sub_path":"OfertaCasas/OfertaCasas/spiders/vivanuncios.py","file_name":"vivanuncios.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"11394944361","text":"# coding=utf-8\r\n\r\nimport requests\r\nimport json\r\nfrom lxml import etree\r\nimport re\r\nfrom urllib import parse\r\n\r\nclass TiebaSpider(object):\r\n def __init__(self, tieba_name):\r\n self.tieba_name = tieba_name\r\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\"}\r\n self.start_url = 'https://tieba.baidu.com/f?ie=utf-8&kw='+tieba_name+'&fr=search&pn=0'\r\n self.part_url = 'http://tieba.baidu.com'\r\n\r\n def parse_url(self, url):\r\n '''发送请求,获取响应'''\r\n print(\"当前请求的地址:\",url)\r\n html_str = requests.get(url, headers=self.headers)\r\n # 带有编码的不能用decode,只能使用byte\r\n html_str = html_str.content.decode()\r\n\r\n sub_str =r'|<--|src=\"http://aod-image.baidu.com/5/pic/9dc7a97299d6060bc027efbe8ba3c67d.jpg\"|src=\"http://aod-image.baidu.com/5/pic/0c11fb54e3361f72ca4d473f3c5be670.jpg\"'\r\n\r\n # 也可以用str.replace('\\n','')替换某些字符\r\n html_str = re.sub(sub_str,'',html_str)\r\n # html_str = html_str.encode()\r\n return html_str\r\n\r\n def get_content_list(self,html_str):\r\n '''提取数据'''\r\n html = etree.HTML(html_str)\r\n # html = re.sub(r\"\",'',html)\r\n\r\n # 或者可以写成\"//ul[@id='frslistcontent']/li[contains(@class,'tl_shadow')]\"\r\n # todo:手机版\r\n # li_list = html.xpath(\"//ul[@id='frslistcontent']/li[@class='tl_shadow tl_shadow_new']\")\r\n # content_list = []\r\n # for li in li_list:\r\n # item = {}\r\n # item['title'] = li.xpath(\".//span[@class='']/text()\")[0] if len(li.xpath(\".//span[@class='']/text()\"))>0 else None\r\n # item['href'] = li.xpath(\".//a/@href\")[0] if len(li.xpath(\".//a/@href\"))>0 else None\r\n # item['img_list'] = self.get_img_list(item['href'])\r\n # content_list.append(item)\r\n # todo:电脑版\r\n # 提取下一页url地址\r\n next_url = html.xpath(\"//a[text()='下一页>']/@href\")[0] if len(\r\n html.xpath(\"//a[text()='下一页>']/@href\")) > 0 else None\r\n\r\n li_list = html.xpath(\"//ul[@id='thread_list']//li[contains(@class,'j_thread_list')]//div[contains(@class,'threadlist_title')]/a\") # 分组\r\n content_list = []\r\n for li in li_list:\r\n item = {}\r\n item['title'] = li.xpath(\"./text()\")[0] if len(li.xpath(\"./text()\"))>0 else None\r\n item['href'] = self.part_url+li.xpath(\"./@href\")[0] if len(li.xpath(\"./@href\"))>0 else None\r\n item['img_list'] = self.get_img_list(item['href'], [])\r\n content_list.append(item)\r\n # 保存\r\n self.save_content_list(content_list)\r\n return content_list, next_url\r\n\r\n\r\n def get_img_list(self, detail_url, total_img_list):\r\n '''获取帖中的所有图片'''\r\n # 3.2 请求列表页的地址,获取详情页第一页\r\n detail_html_str = self.parse_url(detail_url)\r\n detail_html = etree.HTML(detail_html_str)\r\n # print(etree.tostring(detail_html))\r\n # 3.3 提取详情页第一页的图片,提取下一页的地址\r\n img_list = detail_html.xpath(\"//img[@class='BDE_Image']/@src\")\r\n # total_img_list+=img_list\r\n total_img_list.extend(img_list)\r\n # 3.4 请求详情页的下一页地址,进入3.2-3.4循环\r\n detail_next_url =detail_html.xpath(\"//a[text()='下一页']/@href\")\r\n # print(\"当前地址:\",detail_next_url)\r\n if len(detail_next_url)>0:\r\n detail_next_url = self.part_url + detail_next_url[0]\r\n # 递归调用\r\n return self.get_img_list(detail_next_url, total_img_list)\r\n print('-'*100)\r\n # print(total_img_list)\r\n return total_img_list\r\n\r\n def save_content_list(self, content_list):\r\n '''保存数据'''\r\n # file_name = '贴吧爬取每个帖子图片/'+self.tieba_name+'.txt'\r\n file_name = '贴吧爬取每个帖子图片/' + self.tieba_name + '.txt'\r\n with open(file_name,'a', encoding='utf-8') as f:\r\n f.write(json.dumps(content_list[0],ensure_ascii=False,indent=2))\r\n f.write('\\n')\r\n\r\n print('保存成功')\r\n\r\n def run(self):\r\n # 1.start_url\r\n next_url = self.start_url\r\n while next_url is not None:\r\n # 2.发送请求,获取响应\r\n html_str = self.parse_url(next_url)\r\n # 3.提取数据,提取下一页url地址\r\n # 3.1 提取列表页的标题和url地址\r\n # 3.2 请求列表页的地址,获取详情页第一页\r\n # 3.3 提取详情页第一页的图片,提取下一页的地址\r\n # 3.4 请求详情页的下一页地址,进入3.2-3.4循环\r\n content_list, next_url = self.get_content_list(html_str)\r\n # 4.保存数据\r\n self.save_content_list(content_list)\r\n # 5.请求下一页的url地址,进入2-5步循环\r\n\r\n\r\nif __name__ == '__main__':\r\n name = input(\"请输入要爬取的贴吧名:\")\r\n tieba = TiebaSpider(name)\r\n tieba.run()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"giant-xf/myspider","sub_path":"7.0-爬虫(spider)/7.01-通用爬虫模块使用/11-贴吧爬取.py","file_name":"11-贴吧爬取.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"35239171779","text":"import scrapy \n\n\nclass ToScrapeCSSSpider(scrapy.Spider):\n name = \"toscrape\"\n start_urls = [\n 'https://www.coursera.org/courses?',\n ]\n\n def parse(self, response):\n for class_name in response.css('li.ais-InfiniteHits-item'):\n yield{\n 'classname': class_name.css('div.card-info.vertical-box h2.color-primary-text.card-title.headline-1-text::text').get(),\n 'partnet_name':class_name.css('span.partner-name::text').get(),\n 'rating':class_name.css('span.ratings-text::text').get(),\n 'difficulty': class_name.css('span.difficulty::text').get(),\n 'enrollment-number':class_name.css('span.enrollment-number::text').get()\n\n }\n next_page = response.css('li.next a::attr(href)').get()\n if next_page is not None:\n yield response.follow(next_page, callback=self.parse)","repo_name":"anniechen0127/web_scraping","sub_path":"tutorial/spiders/scrapy.py","file_name":"scrapy.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22186334044","text":"import json\nfrom graphene_django.utils.testing import GraphQLTestCase\nfrom unittest.mock import patch\n\nfrom django.db.models import Max\n\nfrom allianceauth.tests.test_auth_utils import AuthUtils\nfrom app_utils.testdata_factories import UserMainFactory, EveCharacterFactory\nfrom app_utils.esi_testing import EsiClientStub, EsiEndpoint\n\nfrom allianceauth.corputils.models import CorpStats, CorpMember\n\n\nclass TestQueriesAndTypes(GraphQLTestCase):\n maxDiff = None\n\n @classmethod\n def setUpTestData(cls):\n cls.user, cls.user2 = UserMainFactory.create_batch(2)\n\n cls.user = AuthUtils.add_permissions_to_user_by_name(\n [\n 'corputils.add_corpstats',\n 'corputils.view_corp_corpstats',\n ],\n cls.user,\n False\n )\n\n cls.mainchar = cls.user.profile.main_character\n cls.corp = cls.mainchar.corporation\n\n cls.newchars = EveCharacterFactory.create_batch(9, corporation=cls.corp)\n\n cls.corpstat = CorpStats.objects.create(\n token=cls.user.token_set.first(),\n corp=cls.corp\n )\n\n cls.corpstat2 = CorpStats.objects.create(\n token=cls.user2.token_set.first(),\n corp=cls.user2.profile.main_character.corporation\n )\n\n CorpMember.objects.bulk_create(\n [\n CorpMember(\n character_id=char.character_id,\n character_name=char.character_name,\n corpstats=cls.corpstat\n ) for char in cls.newchars\n ]\n )\n\n CorpMember.objects.create(\n character_id=cls.mainchar.character_id,\n character_name=cls.mainchar.character_name,\n corpstats=cls.corpstat\n )\n\n def test_get_corpstats(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q {\n corputilsGetAllCorpstats {\n corp {\n id\n }\n }\n }\n '''\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsGetAllCorpstats': [\n {\n 'corp': {\n 'id': str(self.corp.pk)\n }\n }\n ]\n }\n }\n )\n\n def test_get_corpstats_corp_ok(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q($input: Int!) {\n corputilsGetCorpstatsCorp(corpId: $input) {\n corp {\n id\n }\n }\n }\n ''',\n input_data=self.corp.corporation_id\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsGetCorpstatsCorp': {\n 'corp': {\n 'id': str(self.corp.pk)\n }\n }\n }\n }\n )\n\n def test_get_corpstats_corp_not_ok(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q($input: Int!) {\n corputilsGetCorpstatsCorp(corpId: $input) {\n corp {\n id\n }\n }\n }\n ''',\n input_data=self.corpstat2.corp.corporation_id\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsGetCorpstatsCorp': None\n }\n }\n )\n\n def test_search_corpstats(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q($input: String!) {\n corputilsSearchCorpstats(searchString: $input) {\n characterId\n }\n }\n ''',\n input_data=self.mainchar.character_name\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsSearchCorpstats': [\n {\n 'characterId': self.mainchar.character_id\n }\n ]\n }\n }\n )\n\n def test_character_field_ok(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q($input: String!) {\n corputilsSearchCorpstats(searchString: $input) {\n characterId\n character {\n id\n }\n }\n }\n ''',\n input_data=self.mainchar.character_name\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsSearchCorpstats': [\n {\n 'characterId': self.mainchar.character_id,\n 'character': {\n 'id': str(self.mainchar.pk)\n }\n }\n ]\n }\n }\n )\n\n def test_character_field_not_ok(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n max_char_id = CorpMember.objects.aggregate(m=Max('character_id'))['m']\n\n notregisteredmember = CorpMember.objects.create(\n character_id=max_char_id + 1,\n character_name=self.mainchar.character_name + ' 2',\n corpstats=self.corpstat\n )\n\n response = self.query(\n '''\n query q($input: String!) {\n corputilsSearchCorpstats(searchString: $input) {\n characterId\n character {\n id\n }\n }\n }\n ''',\n input_data=notregisteredmember.character_name\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsSearchCorpstats': [\n {\n 'characterId': max_char_id + 1,\n 'character': None\n }\n ]\n }\n }\n )\n\n def test_registered_type(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q {\n corputilsGetAllCorpstats {\n registered {\n id\n }\n }\n }\n '''\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsGetAllCorpstats': [\n {\n 'registered': [\n {\n 'id': str(self.mainchar.pk)\n }\n ]\n }\n ]\n }\n }\n )\n\n def test_unregistered_type(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q {\n corputilsGetAllCorpstats {\n unregistered {\n id\n }\n }\n }\n '''\n )\n\n expected = [str(char.pk) for char in self.newchars]\n\n data = json.loads(response.content)\n\n self.assertIn('data', data)\n self.assertNotIn('errors', data)\n self.assertIn('corputilsGetAllCorpstats', data['data'])\n\n results = data['data']['corputilsGetAllCorpstats']\n\n self.assertEqual(len(results), 1)\n\n results = results[0]['unregistered']\n\n self.assertCountEqual(\n [r['id'] for r in results],\n expected\n )\n\n def test_mains_type(self):\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n query q {\n corputilsGetAllCorpstats {\n mains {\n id\n }\n }\n }\n '''\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsGetAllCorpstats': [\n {\n 'mains': [\n {\n 'id': str(self.mainchar.pk)\n }\n ]\n }\n ]\n }\n }\n )\n\n\nclass TestMutations(GraphQLTestCase):\n maxDiff = None\n\n @classmethod\n def setUpTestData(cls):\n cls.user = UserMainFactory(main_character__scopes=['esi-corporations.read_corporation_membership.v1'])\n\n cls.user = AuthUtils.add_permission_to_user_by_name(\n 'corputils.add_corpstats',\n cls.user,\n False\n )\n\n cls.token = cls.user.token_set.first()\n\n @patch('allianceauth.corputils.models.CorpStats.update')\n def test_add_corp_stats_mutation_ok(self, mock_update):\n mock_update.return_value = None\n\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n mutation m($input: ID!) {\n corputilsAddCorpstats(tokenId: $input) {\n ok\n }\n }\n ''',\n input_data=self.token.pk\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsAddCorpstats': {\n 'ok': True\n }\n }\n }\n )\n\n self.assertTrue(mock_update.called)\n\n def test_add_corp_stats_mutation_wrong_user(self):\n user2 = UserMainFactory()\n\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n mutation m($input: ID!) {\n corputilsAddCorpstats(tokenId: $input) {\n ok\n }\n }\n ''',\n input_data=user2.token_set.first().pk\n )\n\n data = json.loads(response.content)\n\n self.assertIn('data', data)\n self.assertIn('errors', data)\n self.assertIn('corputilsAddCorpstats', data['data'])\n self.assertIsNone(data['data']['corputilsAddCorpstats'])\n\n self.assertEqual(len(data['errors']), 1)\n\n error = data['errors'][0]\n\n self.assertIn('locations', error)\n self.assertIn('path', error)\n self.assertIn('message', error)\n\n self.assertEqual(error['path'], ['corputilsAddCorpstats'])\n\n self.assertEqual(error['message'], 'Token not valid')\n\n def test_add_corp_stats_mutation_token_missing(self):\n user2 = UserMainFactory()\n\n user2 = AuthUtils.add_permission_to_user_by_name(\n 'corputils.add_corpstats',\n user2,\n False\n )\n\n self.client.force_login(user2, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n mutation m($input: ID!) {\n corputilsAddCorpstats(tokenId: $input) {\n ok\n }\n }\n ''',\n input_data=user2.token_set.first().pk\n )\n\n data = json.loads(response.content)\n\n self.assertIn('data', data)\n self.assertIn('errors', data)\n self.assertIn('corputilsAddCorpstats', data['data'])\n self.assertIsNone(data['data']['corputilsAddCorpstats'])\n\n self.assertEqual(len(data['errors']), 1)\n\n error = data['errors'][0]\n\n self.assertIn('locations', error)\n self.assertIn('path', error)\n self.assertIn('message', error)\n\n self.assertEqual(error['path'], ['corputilsAddCorpstats'])\n\n self.assertEqual(error['message'], 'Required token missing')\n\n @patch('esi.models.Token.get_esi_client')\n @patch('allianceauth.corputils.models.CorpStats.update')\n def test_add_corp_stats_mutation_character_not_exists(self, mock_update, mock_esi_client):\n mock_update.return_value = None\n\n mock_endpoint = EsiEndpoint(\n 'Character',\n 'get_characters_character_id',\n 'character_id',\n data={\n str(self.token.character_id): {\n 'corporation_id': self.user.profile.main_character.corporation_id\n }\n }\n )\n\n mock_esi_client.return_value = EsiClientStub.create_from_endpoints([mock_endpoint])\n\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n self.user.profile.main_character.delete()\n\n response = self.query(\n '''\n mutation m($input: ID!) {\n corputilsAddCorpstats(tokenId: $input) {\n ok\n }\n }\n ''',\n input_data=self.token.pk\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsAddCorpstats': {\n 'ok': True\n }\n }\n }\n )\n\n self.assertTrue(mock_update.called)\n\n @patch('esi.clients.esi_client_factory')\n @patch('allianceauth.corputils.models.CorpStats.update')\n def test_add_corp_stats_mutation_corp_not_exists(self, mock_update, mock_esi_client):\n mock_update.return_value = None\n\n corp = self.user.profile.main_character.corporation\n\n mock_endpoint = EsiEndpoint(\n 'Corporation',\n 'get_corporations_corporation_id',\n 'corporation_id',\n data={\n str(corp.corporation_id): {\n 'name': corp.corporation_name,\n 'ticker': corp.corporation_ticker,\n 'member_count': corp.member_count,\n 'alliance_id': corp.alliance_id,\n }\n }\n )\n\n mock_esi_client.return_value = EsiClientStub.create_from_endpoints([mock_endpoint])\n\n corp.delete()\n\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n response = self.query(\n '''\n mutation m($input: ID!) {\n corputilsAddCorpstats(tokenId: $input) {\n ok\n }\n }\n ''',\n input_data=self.token.pk\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsAddCorpstats': {\n 'ok': True\n }\n }\n }\n )\n\n self.assertTrue(mock_update.called)\n\n @patch('allianceauth.corputils.models.CorpStats.update')\n def test_update_corpstats_ok(self, mock_update):\n mock_update.return_value = None\n\n self.client.force_login(self.user, \"graphql_jwt.backends.JSONWebTokenBackend\")\n\n corp = self.user.profile.main_character.corporation\n\n CorpStats.objects.create(\n token=self.token,\n corp=corp\n )\n\n response = self.query(\n '''\n mutation m($input: Int!) {\n corputilsUpdateCorpstats(corpId: $input) {\n ok\n }\n }\n ''',\n input_data=corp.corporation_id\n )\n\n self.assertJSONEqual(\n response.content,\n {\n 'data': {\n 'corputilsUpdateCorpstats': {\n 'ok': True\n }\n }\n }\n )\n\n self.assertTrue(mock_update.called)\n","repo_name":"Maestro-Zacht/allianceauth-graphql","sub_path":"allianceauth_graphql/tests/test_corputils.py","file_name":"test_corputils.py","file_ext":"py","file_size_in_byte":16747,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"10297671916","text":"#\n# README: please install the library before use\n# : Require Libraries:\n# MQTT https://pypi.python.org/pypi/paho-mqtt\n# matplotlib http://matplotlib.org/\n# It's easiler if you just install http://continuum.io/\n# Features:\n# Plot sensor data in realtime.\n# Support device_id filter.\n# User configuable by modify the setting in the code.\n# Author:\n# Wuulong, Created 28/06/2015 \n# https://github.com/LinkItONEDevGroup/LASS\nimport paho.mqtt.client as mqtt\n#plot\nimport matplotlib.pyplot as plt\nimport datetime\n\nVERSION=0.01\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n #client.subscribe(\"$SYS/#\")\n #topic=\"Sensors/#\"\n client.subscribe(setting.mqtt_topic, qos=0)\n\n# The callback for when a PUBLISH message is received from the server.\ndef on_message(client, userdata, msg):\n print(msg.topic+\" \"+str(msg.payload))\n sensor_datas.add(msg.payload)\n sensor_plot.plot()\n \n# the setting for the program\nclass Setting:\n def __init__(self):\n #system general setting\n self.debug_enable=0 #0: debug disable , 1: debug enable\n self.plot_cnt=90 # the value count in plotter, if 10 seconds for 1 value, about 15 min.\n \n self.mqtt_topic=\"Sensors/SoundSensor\" #REPLACE: to your sensor topic\n self.device_id=\"LASS-Example\"\n self.filter_deviceid_enable=0 # the filter make you focus on this device_id\n \n# Sensor plot funcition \nclass SensorPlot:\n def __init__(self):\n self.first=1 # first run\n\n def init(self):\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(111)\n def plot(self):\n x, y = sensor_datas.get_values(setting.plot_cnt)\n\n if self.first:\n self.init()\n plt.title(setting.mqtt_topic + ' Sensor data')\n plt.ylabel('Sensor value')\n plt.xlabel(\"Data Receive time\")\n plt.gcf().autofmt_xdate()\n (self.li, )= self.ax.plot(x, y)\n \n # draw and show it\n self.fig.canvas.draw()\n plt.show(block=False)\n else:\n self.li.set_xdata(x)\n self.li.set_ydata(y)\n self.fig.canvas.draw()\n \n\n\n \n#Spec: Sensor data default handler\nclass SensorDatas:\n def __init__(self):\n self.datas=[]\n \n def add(self,payload):\n sensor_data = SensorData(payload)\n self.datas.append(sensor_data)\n print(sensor_data.get_value())\n #self.desc()\n def get_values(self,latest_cnt):\n values_x = []\n values_y = []\n for data in self.datas:\n if data.valid==1:\n value_x = data.localtime\n value_y = float(data.get_value())\n values_x.append(value_x)\n values_y.append(value_y)\n \n return (values_x[-latest_cnt:], values_y[-latest_cnt:])\n \n def desc(self):\n for data in self.datas:\n print(data.raw)\n\n#Spec: Sensor data default handler\nclass SensorData:\n def __init__(self,payload):\n #example payload \n #|device_id=LASS-Wuulong|time=2474079|device=LinkItONE|values=14|gps=$GPGGA,103106.000,2448.0291,N,12059.5732,E,1,4,5.89,29.9,M,15.0,M,,*63\n self.raw = payload\n self.valid=0 # only use data when valid=1\n self.localtime=datetime.datetime.now()\n\n # parameters valid after data_processing\n self.value_dict={} # value is string type\n \n self.data_process()\n self.check_valid()\n \n def data_process(self):\n cols=self.raw.split(\"|\")\n for col in cols:\n if setting.debug_enable:\n print(\"col:\" + col)\n pars = col.split(\"=\")\n if len(pars)>=2:\n self.value_dict[pars[0]] = pars[1]\n #check if data valid and apply filter\n def check_valid(self):\n if setting.filter_deviceid_enable==1:\n if self.value_dict[\"device_id\"]==setting.device_id:\n self.valid=1\n else:\n self.valid=0\n else:\n self.valid=1\n def get_value(self): # currently return \"\" if not valid. The return type is string\n if self.valid!=1:\n return \"\"\n return self.value_dict[\"values\"]\n\nprint(\"----- LASS V\" + str(VERSION) + \" -----\")\n\nsetting = Setting() \nsensor_datas = SensorDatas() \nsensor_plot = SensorPlot() \nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(\"gpssensor.ddns.net\", 1883, 60)\n\n \n# Blocking call that processes network traffic, dispatches callbacks and\n# handles reconnecting.\n# Other loop*() functions are available that give a threaded interface and a\n# manual interface.\nclient.loop_forever()\n\n\n\n\n\n","repo_name":"LinkItONEDevGroup/LASS","sub_path":"DataPresentation/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","stars":156,"dataset":"github-code","pt":"85"} +{"seq_id":"7314203603","text":"import random\r\nwbank = ['u','r','a','butt','i','am','the','boy','we','like','to','scream','u','r','a','butt','i','am','the','boy','we','like','to','scream','u','r','a','butt','i','am','the','boy','we','like','to','scream']\r\nccap = 10\t\t\t\t\t\t\t\t#have this be a user inputted variable.\r\ndef sentencegen (words,hardcap):\t\t#takes a string of words and creates a randomly arranged 'sentence'\r\n\twordcap = len(words)\r\n\tsntgen=0\r\n\ttemprand = 0\r\n\twhile (wordcap > 1) and (sntgen < hardcap):\t\t\t\t\t#this is giving me problems but i want a blank sentence everytime this loop restarts\r\n\t\twordcap = len(words)\t\t\t#wordcap dynamically refreshes per loop which is why its at the beginning\r\n\t\tsenlen = random.randint(2,17)\t#these are just arbitrary numbers dont worry about it\r\n\t\tinf = False\t\t\t\t\t\t#inf will activate if hardcap is -1\r\n\t\tdie = False\t\t\t\t\t\t#this basically ends the loop with a break to prevent bugs\r\n\t\tif (wordcap < 17) and (wordcap >1):\r\n\t\t\tsenlen = wordcap\r\n\t\t\tprint(\"out of words\")\r\n\t\t\tdie = True\r\n\t\twhile (senlen > 0):\t\t\t\t#Will add words until the sentence length value is satisfied\r\n\t\t\ttemprand = random.randint(0,senlen)\t#i literally forgot why i set the upper limit to sentence length maybe it makes sense to you\r\n\t\t\tif (temprand < senlen):\r\n\t\t\t\ttempword = words[temprand]\r\n\t\t\t\tsntc.append(tempword)\r\n\t\t\t\twordcap =-1\r\n\t\t\telif inf is False:\r\n\t\t\t\tdel words[temprand-1]\t#deletion from list should occur if -1 isnt the cap\r\n\t\t\tsenlen =-1\t\t\t\t\t#makes this loop not explode\r\n\t\t\tsntgen =+ 1\t\t\t\t\t#same\r\n\t\tprint(sntc)\t\t\t\t\t\t#this is doodoo dicks formatting but i could make it look prettier if i had time\r\n\t\tif die is True:\r\n\t\t\tbreak\t\t\t\t\t\t#in case we run out of words this is the break from the loop\r\n\r\nsentencegen(wbank,ccap) \t\t\t\t#2 inputs: the actual word bank, and the cap of sentences you want","repo_name":"tangylyre/hahaxd","sub_path":"abcde.py","file_name":"abcde.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20129215822","text":"from kafka import KafkaProducer\nfrom json import dumps\nimport time\n\n\n# dict(key,value) -> object\n# str -> string\n\nproducer = KafkaProducer(acks=0, \n compression_type='gzip',\n bootstrap_servers=['127.0.0.1:9092'],\n value_serializer=lambda x : dumps(x).encode('utf-8'))\n\nstart = time.time()\ndata = {\"schema\":{\"type\":\"struct\",\"fields\":[{\"type\":\"int32\",\"field\":\"id\"},{\"type\":\"string\",\"field\":\"user_id\"},{\"type\":\"string\",\"field\":\"NAME\"}],\"name\":\"users\"},\"payload\":{\"id\":114,\"user_id\":\"6democratickim9\",\"NAME\":\"minjju\"}}\nproducer.send('minju_exam_topic_users', value=data)\nproducer.flush()\n\nprint(\"Done. Elapsed time: \", (time.time() - start))","repo_name":"6democratickim9/multi_work","sub_path":"playbook_kafaka/kafka_producer.py","file_name":"kafka_producer.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29822348273","text":"# Simple Python script to compare approximations (such as EDV) with full simulations.\n# by Alberto Tonda, 2018 \n\nimport argparse\nimport matplotlib\nimport numpy as np\nimport os\nimport re as regex\nimport sys\n\nmatplotlib.use(\"Agg\") # I don't really know what it does...\n\nimport matplotlib.animation as manimation \nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm \n\n# import a couple of utility things in a relative path\nsys.path.append(\"../approximations\")\nimport SNSigmaSim_networkx as simulations\nimport SNSigmaApprox_networkx as approximations\n\ndef loadPointsFromFile(fileName) :\n\t\n\tlines = []\n\twith open(fileName, \"r\") as fp : lines = fp.readlines()\n\tlines.pop(0) # remove header\n\t\n\tpoints = []\n\tfor line in lines :\n\t\ttokens = line.rstrip().split(',')\n\t\tpoints.append( [ int(float(x)) for x in tokens[2:] ] ) \n\t\n\treturn points\n\ndef computeFitnessFront(G, simulationPoints, probability, numberOfRepetitions, simulationModel) :\n\t\n\tfitness = []\n\tfor i in range(0, len(simulationPoints)) : # TODO modify here for shorter trial runs\n\t\tprint(\"Running simulation for point %d/%d...\" % (i+1, len(simulationPoints)))\n\t\tfitness.append( (len(simulationPoints[i]), simulations.evaluate(G, simulationPoints[i], probability, numberOfRepetitions, simulationModel)[0]) )\n\n\treturn fitness\n\ndef main() :\n\t\n\t# a few hard-coded default values\n\tnumberOfRepetitions = 100\n\tsimulationModel = 'IC'\n\tprobability = 0.01\n\tfileSimulations = \"simulations.csv\"\n\t\n\t# parse arguments: there might be several heuristics\n\tparser = argparse.ArgumentParser(description=\"Python script to compare influence maximization with approximations or simulations.\\nBy Doina Bucur, Giovanni Iacca, Andrea Marcelli, Giovanni Squillero, Alberto Tonda, 2018 \")\t\n\t\n\tparser.add_argument(\"-a\", \"--approximations\", nargs='+', help=\"List of CSV files with points in a Pareto front, obtained by different approximations. Supports a list of tuples ...\", required=True)\n\tparser.add_argument(\"-s\", \"--simulation\", help=\"CSV files with points in a Pareto front, obtained by simulation.\", required=True)\n\tparser.add_argument(\"-g\", \"--graph\", help=\"Name of the graph. Used to re-run the points find by the approximations.\")\n\tparser.add_argument(\"-hu\", \"--heuristics\", nargs='+', help=\"List of CSV files with points in a Pareto front, obtained by different heuristics. Supports a list of tuples ...\")\n\t\n\t# TODO simulation type (IC/WC) and probability\n\t# TODO graph directed/undirected? \n\t# TODO number of simulations?\n\t\n\targs = parser.parse_args()\n\t\n\t# extra check: the list of arguments for --approximations has to be even\n\tif len(args.approximations) % 2 != 0 :\n\t\tsys.stderr.write(\"Error: the list of approximations should follow the scheme ...\")\n\t\tsys.exit(0)\n\t\n\t# load the graph\n\tprint(\"Loading graph \\\"%s\\\"...\" % args.graph)\n\tG = approximations.read_undirected_graph(args.graph)\n\t\n\t# this dictionary will store all the Pareto fronts to be later plotted\n\tparetoFronts = dict()\n\t\n\t# read the simulation Pareto front\n\tprint(\"Loading and running simulation Pareto front \\\"%s\\\"...\" % args.simulation)\n\t\n\tif not os.path.exists(fileSimulations) :\n\t\tsimulationPoints = loadPointsFromFile(args.simulation)\n\t\tparetoFronts[\"Simulations \" + simulationModel] = computeFitnessFront(G, simulationPoints, probability, numberOfRepetitions, simulationModel)\n\t\t\n\t\twith open(fileSimulations, \"w\") as fp :\n\t\t\tfp.write(\"size,influence\\n\")\n\t\t\tfor point in paretoFronts[\"Simulations \" + simulationModel] :\n\t\t\t\tfp.write( str(point[0]) + \",\" + str(point[1]) + \"\\n\")\n\t\n\telse :\n\t\tprint(\"Found file called \\\"%s\\\": loading values from there...\" % fileSimulations)\n\t\twith open(fileSimulations, \"r\") as fp :\n\t\t\tlines = fp.readlines()\n\t\t\tlines.pop(0) # remove header\n\t\t\t\n\t\t\tparetoFronts[\"Simulations \" + simulationModel] = []\n\t\t\tfor line in lines :\n\t\t\t\ttokens = line.rstrip().split(',')\n\t\t\t\tparetoFronts[\"Simulations \" + simulationModel].append( (int(tokens[0]), float(tokens[1])) )\n\t\n\t# let's go with the approximations! \n\ti = 0\n\twhile i < len(args.approximations) :\n\t\tprint(\"Loading and running approximation Pareto front \\\"%s\\\"...\" % args.approximations[i+1])\n\t\tfileApproximation = args.approximations[i] + \".csv\"\n\t\t\n\t\tif not os.path.exists(fileApproximation) :\n\t\t\tpoints = loadPointsFromFile( args.approximations[i+1] )\n\t\t\tparetoFronts[args.approximations[i]] = computeFitnessFront(G, points, probability, numberOfRepetitions, simulationModel)\n\t\t\n\t\t\twith open(fileApproximation, \"w\") as fp :\n\t\t\t\tfp.write(\"size,influence\\n\")\n\t\t\t\tfor point in paretoFronts[args.approximations[i]] :\n\t\t\t\t\tfp.write( str(point[0]) + \",\" + str(point[1]) + \"\\n\")\n\t\t\n\t\telse :\n\t\t\tprint(\"Found approximation file \\\"%s\\\", loading values from there...\" % fileApproximation)\n\t\t\t\n\t\t\twith open(fileApproximation, \"r\") as fp :\n\t\t\t\tlines = fp.readlines()\n\t\t\t\tlines.pop(0)\n\t\t\t\t\n\t\t\t\tparetoFronts[args.approximations[i]] = []\n\t\t\t\tfor line in lines :\n\t\t\t\t\ttokens = line.rstrip().split(',')\n\t\t\t\t\tparetoFronts[args.approximations[i]].append( (int(tokens[0]), float(tokens[1])) )\n\t\ti += 2\n\t\n\t# finally, let's plot everything!\n\tfig = plt.figure()\n\tax = plt.subplot(111)\n\t\n\t# let's create a rainbow cycle, using matplotlib's color map, that will be used for colors later\n\tcolor = cm.rainbow( np.linspace(0, 1, len(paretoFronts)) )\n\n\tkeys = [ k for k in paretoFronts ]\n\tprint(\"Keys:\", keys)\n\tfor i in range(0, len(keys)) :\n\t\tx = [ a[1] for a in paretoFronts[keys[i]] ]\n\t\ty = [ a[0] for a in paretoFronts[keys[i]] ]\n\t\t#print(\"x for \" + keys[i] + \":\", x)\n\t\t#print(\"y for \" + keys[i] + \":\", y)\n\t\tax.plot(x, y, '.', c=color[i], label=keys[i])\n\n\tax.set_xlabel(\"influence\")\n\tax.set_ylabel(\"nodes in the seed set\")\n\tax.set_title(\"Comparison of simulation vs heuristics\")\n\tax.legend(loc='best')\n\t\n\tplt.savefig(\"compareApproximations.pdf\")\n\t\n\treturn\n\nif __name__ == \"__main__\" :\n\tsys.exit( main() )\n","repo_name":"albertotonda/Influence-Maximization","sub_path":"src_OLD/utils/compareApproximations.py","file_name":"compareApproximations.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"85"} +{"seq_id":"12216085861","text":"import os\nimport sys\nimport time\nimport uuid\nimport json\nimport logging\nimport argparse\nfrom AWSIoTPythonSDK.core.greengrass.discovery.providers import DiscoveryInfoProvider\nfrom AWSIoTPythonSDK.core.protocol.connection.cores import ProgressiveBackOffCore\nfrom AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient\nfrom AWSIoTPythonSDK.exception.AWSIoTExceptions import DiscoveryInvalidRequestException\n\n\nAllowedActions = ['both', 'publish', 'subscribe']\n\n# General message notification callback\ndef customOnMessage(message):\n print('Received message on topic %s: %s\\n' % (message.topic, message.payload))\n\nMAX_DISCOVERY_RETRIES = 10\nGROUP_CA_PATH = \"./groupCA/\"\n\n# Read in command-line parameters\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-e\", \"--endpoint\", action=\"store\", required=True, dest=\"host\", help=\"Your AWS IoT custom endpoint\")\nparser.add_argument(\"-r\", \"--rootCA\", action=\"store\", required=True, dest=\"rootCAPath\", help=\"Root CA file path\")\nparser.add_argument(\"-c\", \"--cert\", action=\"store\", dest=\"certificatePath\", help=\"Certificate file path\")\nparser.add_argument(\"-k\", \"--key\", action=\"store\", dest=\"privateKeyPath\", help=\"Private key file path\")\nparser.add_argument(\"-n\", \"--thingName\", action=\"store\", dest=\"thingName\", default=\"Bot\", help=\"Targeted thing name\")\nparser.add_argument(\"-t\", \"--topic\", action=\"store\", dest=\"topic\", default=\"sdk/test/Python\", help=\"Targeted topic\")\nparser.add_argument(\"-m\", \"--mode\", action=\"store\", dest=\"mode\", default=\"both\",\n help=\"Operation modes: %s\"%str(AllowedActions))\nparser.add_argument(\"-M\", \"--message\", action=\"store\", dest=\"message\", default=\"Hello World!\",\n help=\"Message to publish\")\n\nargs = parser.parse_args()\nhost = args.host\nrootCAPath = args.rootCAPath\ncertificatePath = args.certificatePath\nprivateKeyPath = args.privateKeyPath\nclientId = args.thingName\nthingName = args.thingName\ntopic = args.topic\n\nif args.mode not in AllowedActions:\n parser.error(\"Unknown --mode option %s. Must be one of %s\" % (args.mode, str(AllowedActions)))\n exit(2)\n\nif not args.certificatePath or not args.privateKeyPath:\n parser.error(\"Missing credentials for authentication, you must specify --cert and --key args.\")\n exit(2)\n\nif not os.path.isfile(rootCAPath):\n parser.error(\"Root CA path does not exist {}\".format(rootCAPath))\n exit(3)\n\nif not os.path.isfile(certificatePath):\n parser.error(\"No certificate found at {}\".format(certificatePath))\n exit(3)\n\nif not os.path.isfile(privateKeyPath):\n parser.error(\"No private key found at {}\".format(privateKeyPath))\n exit(3)\n\n# Configure logging\n#logger = logging.getLogger(\"AWSIoTPythonSDK.core\")\n#logger.setLevel(logging.DEBUG)\n#streamHandler = logging.StreamHandler()\n#formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n#streamHandler.setFormatter(formatter)\n#logger.addHandler(streamHandler)\n\n# Progressive back off core\nbackOffCore = ProgressiveBackOffCore()\n\n# Discover GGCs\ndiscoveryInfoProvider = DiscoveryInfoProvider()\ndiscoveryInfoProvider.configureEndpoint(host)\ndiscoveryInfoProvider.configureCredentials(rootCAPath, certificatePath, privateKeyPath)\ndiscoveryInfoProvider.configureTimeout(10) # 10 sec\n\nretryCount = MAX_DISCOVERY_RETRIES\ndiscovered = False\ngroupCA = None\ncoreInfo = None\nwhile retryCount != 0:\n try:\n discoveryInfo = discoveryInfoProvider.discover(thingName)\n caList = discoveryInfo.getAllCas()\n coreList = discoveryInfo.getAllCores()\n\n # We only pick the first ca and core info\n groupId, ca = caList[0]\n coreInfo = coreList[0]\n #print(\"Discovered GGC: %s from Group: %s\" % (coreInfo.coreThingArn, groupId))\n\n #print(\"Now we persist the connectivity/identity information...\")\n groupCA = GROUP_CA_PATH + groupId + \"_CA_\" + str(uuid.uuid4()) + \".crt\"\n if not os.path.exists(GROUP_CA_PATH):\n os.makedirs(GROUP_CA_PATH)\n groupCAFile = open(groupCA, \"w\")\n groupCAFile.write(ca)\n groupCAFile.close()\n\n discovered = True\n #print(\"Now proceed to the connecting flow...\")\n break\n except DiscoveryInvalidRequestException as e:\n print(\"Invalid discovery request detected!\")\n print(\"Type: %s\" % str(type(e)))\n print(\"Error message: %s\" % e.message)\n print(\"Stopping...\")\n break\n except BaseException as e:\n print(\"Error in discovery!\")\n print(\"Type: %s\" % str(type(e)))\n print(\"Error message: %s\" % e.message)\n retryCount -= 1\n print(\"\\n%d/%d retries left\\n\" % (retryCount, MAX_DISCOVERY_RETRIES))\n print(\"Backing off...\\n\")\n backOffCore.backOff()\n\nif not discovered:\n print(\"Discovery failed after %d retries. Exiting...\\n\" % (MAX_DISCOVERY_RETRIES))\n sys.exit(-1)\n\n# Iterate through all connection options for the core and use the first successful one\nmyAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)\nmyAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath)\nmyAWSIoTMQTTClient.onMessage = customOnMessage\n\nconnected = False\nfor connectivityInfo in coreInfo.connectivityInfoList:\n currentHost = connectivityInfo.host\n currentPort = connectivityInfo.port\n #print(\"Trying to connect to core at %s:%d\" % (currentHost, currentPort))\n myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)\n try:\n myAWSIoTMQTTClient.connect()\n connected = True\n break\n except BaseException as e:\n print(\"Error in connect!\")\n print(\"Type: %s\" % str(type(e)))\n print(\"Error message: %s\" % e.message)\n\nif not connected:\n print(\"Cannot connect to core %s. Exiting...\" % coreInfo.coreThingArn)\n sys.exit(-2)\n\n# Successfully connected to the core\nif args.mode == 'both' or args.mode == 'subscribe':\n myAWSIoTMQTTClient.subscribe(topic, 0, None)\ntime.sleep(2)\n\nloopCount = 0\n# while True:\n# if args.mode == 'both' or args.mode == 'publish':\n# message = {}\n# message['message'] = args.message\n# message['sequence'] = loopCount\n# messageJson = json.dumps(message)\n# myAWSIoTMQTTClient.publish(topic, messageJson, 0)\n# if args.mode == 'publish':\n# print('Published topic %s: %s\\n' % (topic, messageJson))\n# loopCount += 1\n# time.sleep(1)\n\nfrom AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient\nimport time\nimport json\nimport pandas as pd\nimport datetime\nimport numpy as np\nfrom threading import Lock\n\ndevice_st = 0\ndevice_end = 500\n\n#Path to the dataset, modify this\ndata_path = \"data/class_{}.csv\"\n\n#Path to your certificates, modify this\ncertificate_formatter = \"certificates/thing_{}.certificate.pem\"\nkey_formatter = \"certificates/thing_{}.private.pem\"\n\n\nclass MQTTClient:\n\tdef __init__(self, device_id, cert, key):\n\t\tself.device_id = str(device_id)\n\t\tself.state = 0\n\t\tself.client = AWSIoTMQTTClient(self.device_id)\n\t\tself.client.configureEndpoint(\"a191olynvpydfg-ats.iot.us-west-2.amazonaws.com\", 8883)\n\t\tself.client.configureCredentials(\"root-ca-cert.pem\", key, cert)\n\t\tself.client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing\n\t\tself.client.configureDrainingFrequency(2) # Draining: 2 Hz\n\t\tself.client.configureConnectDisconnectTimeout(10) # 10 sec\n\t\tself.client.configureMQTTOperationTimeout(5) # 5 sec\n\t\tself.client.onMessage = self.customOnMessage\n\n\n\tdef customOnMessage(self,message):\n\t\tprint(\"client {} received prediction {} \\n\".format(self.device_id, json.loads(message.payload)[\"prediction\"]))\n\t\tself.client.disconnectAsync()\n\n\n\t# Suback callback\n\tdef customSubackCallback(self,mid, data):\n\t pass\n\n\n\t# Puback callback\n\tdef customPubackCallback(self,mid):\n\t pass\n\n\n\tdef publish(self):\n\t\tself.client.connect()\n\t\tself.client.subscribeAsync(self.device_id, 1, ackCallback=self.customSubackCallback)\n\n\t\tindex = np.random.randint(0, len(data[self.state]))\n\t\tpayload = {\n\t\t\t\"device_id\": self.device_id,\n\t\t\t\"class\": str(self.state),\n\t\t\t\"features\": list(data[self.state].iloc[index].values)\n\t\t}\n\t\tself.client.publishAsync(\"data/heartbeat\", json.dumps(payload), 0, ackCallback=self.customPubackCallback)\n\n\n\n\n\n# Don't change the code below\nprint(\"wait\")\nlock = Lock()\ndata = []\nfor i in range(5):\n\ta = pd.read_csv(data_path.format(i))\n\tdata.append(a)\n\nclients = []\nfor device_id in range(device_st, device_end):\n\tclient = MQTTClient(device_id,certificate_formatter.format(device_id,device_id) ,key_formatter.format(device_id,device_id))\n\tclients.append(client)\n\n\n\nstates_for_test = [3, 0, 0, 0, 4, 0, 0, 1, 0, 0, 0, 4, 4, 0, 0, 3, 2, 3, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\\\n 0, 0, 0, 4, 0, 4, 3, 0, 0, 3, 0, 2, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0,\\\n 2, 4, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 4, 1, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,\\\n 0, 1, 0, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0,\\\n 0, 0, 4, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 2, 0, 4, 0, 3, 0,\\\n 0, 4, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0,\\\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 2,\\\n 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 2, 0, 0, 0, 0,\\\n 0, 1, 2, 1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 1, 0, 3, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,\\\n 0, 0, 4, 4, 0, 0, 0, 4, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 1, 2, 0, 0,\\\n 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 4, 0, 0,\\\n 0, 4, 1, 1, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,\\\n 2, 0, 2, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 0, 0, 0, 0, 0, 0, 0, 4]\n\ns1,s2,s3,s4 = [],[],[],[]\nfor i in range(device_st,device_end):\n\tif i < 500:\n\t\tclients[i].state = states_for_test[i]\n\t\tif states_for_test[i] == 1: s1.append(i)\n\t\telif states_for_test[i] == 2: s2.append(i)\n\t\telif states_for_test[i] == 3: s3.append(i)\n\t\telif states_for_test[i] == 4: s4.append(i)\n\n\nprint(\"Users at state 1: \", s1)\nprint(\"Users at state 2: \", s2)\nprint(\"Users at state 3: \", s3)\nprint(\"Users at state 4: \", s4)\n\n\n\nprint(\"send now?\")\nx = input()\nif x == \"s\":\n\tfor i,c in enumerate(clients):\n\t\tc.publish()\nelif x == \"d\":\n\tfor c in clients:\n\t\tc.disconnect()\n\t\tprint(\"All devices disconnected\")\nelse:\n\tprint(\"wrong key pressed\")\n\ntime.sleep(10)\n","repo_name":"yilimail/CS498_IOT_Lab4","sub_path":"watch_sim.py","file_name":"watch_sim.py","file_ext":"py","file_size_in_byte":10767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"74725750677","text":"from __future__ import print_function\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nfrom model.Generator import Generator\n#from utils.dataset import Facades\nimport numpy as np\nfrom scipy import misc\n\nparser = argparse.ArgumentParser(description='test pix2pix model')\nparser.add_argument('--batchSize', type=int, default=1, help='input batch size')\nparser.add_argument('--cuda', action='store_true', help='enables cuda')\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--manualSeed', type=int, help='manual seed')\nparser.add_argument('--loadSize', type=int, default=256, help='scale image to this size')\nparser.add_argument('--fineSize', type=int, default=256, help='random crop image to this size')\nparser.add_argument('--input_nc', type=int, default=3, help='channel number of input image')\nparser.add_argument('--output_nc', type=int, default=3, help='channel number of output image')\nparser.add_argument('--flip', type=int, default=0, help='1 for flipping image randomly, 0 for not')\nparser.add_argument('--dataPath', default='facades/test/', help='path to training images')\nparser.add_argument('--which_direction', default='AtoB', help='AtoB or BtoA')\nparser.add_argument('--outf', default='samples/', help='folder to output images and model checkpoints')\nparser.add_argument('--ngf', type=int, default=64)\nparser.add_argument('--imgNum', type=int, default=32, help='How many images to generate?')\n\nopt = parser.parse_args()\nprint(opt)\n\ntry:\n os.makedirs(opt.outf)\nexcept OSError:\n pass\n\nif opt.manualSeed is None:\n opt.manualSeed = random.randint(1, 10000)\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\nif opt.cuda:\n torch.cuda.manual_seed_all(opt.manualSeed)\n\ncudnn.benchmark = True\n\n########### Load netG ###########\nassert opt.netG != '', \"netG must be provided!\"\nnetG = Generator(opt.input_nc, opt.output_nc, opt.ngf)\nnetG.load_state_dict(torch.load(opt.netG))\n########### Generate ###########\n#facades = Facades(opt.dataPath,opt.loadSize,opt.fineSize,opt.flip)\ndataset = np.load('data/radar_2000.npy') \ndataset = dataset/16.0\ntrain_loader = torch.utils.data.DataLoader(dataset=dataset,\n batch_size=opt.batchSize,\n shuffle=True,\n num_workers=2)\n\ninput_nc = opt.input_nc\nfineSize = opt.fineSize\n\nreal_A = torch.FloatTensor(opt.batchSize, input_nc, fineSize, fineSize)\nreal_B = torch.FloatTensor(opt.batchSize, input_nc, fineSize, fineSize)\nreal_A = Variable(real_A)\nreal_B = Variable(real_B)\n\nif(opt.cuda):\n netG.cuda()\n real_A = real_A.cuda()\n real_B = real_B.cuda()\n\nfor i, image in enumerate(train_loader):\n if(opt.which_direction == 'AtoB'):\n imgA = image[:,:3]\n imgB = image[:,3:]\n else:\n imgA = image[:,:3]\n imgB = image[:,3:]\n real_A.data.resize_(imgA.size()).copy_(imgA)\n fake1 = netG(real_A)\n fake2 = netG(fake1)\n fake3 = netG(fake2)\n num = 0\n A = real_A.cpu().data.numpy()\n B = fake1.cpu().data.numpy()\n C = fake2.cpu().data.numpy()\n D = fake3.cpu().data.numpy()\n for n in range(3):\n misc.imsave('%s/%d_%d.png' % (opt.outf,i,num),A[0,n])\n num +=1\n for n in range(3):\n misc.imsave('%s/%d_%d.png' % (opt.outf,i,num),B[0,n])\n num +=1\n for n in range(3):\n misc.imsave('%s/%d_%d.png' % (opt.outf,i,num),C[0,n])\n num +=1\n for n in range(3):\n misc.imsave('%s/%d_%d.png' % (opt.outf,i,num),D[0,n])\n num +=1\n \n\n# fakeB[i,:,:,:] = fake.data\n# A[i,:,:,:] = imgA.data\n# realB[i,:,:,:] = imgB\n#\n if(i+1 >= opt.imgNum):\n break\n#\n#vutils.save_image(fakeB,\n# '%s/fakeB.png' % (opt.outf),\n# normalize=True,\n# scale_each=True)\n#vutils.save_image(A,\n# '%s/A.png' % (opt.outf),\n# normalize=True,\n# scale_each=True)\n#vutils.save_image(realB,\n# '%s/realB.png' % (opt.outf),\n# normalize=True,\n# scale_each=True)\n","repo_name":"xi-studio/predict-radar","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"8335569773","text":"from django.shortcuts import render\nfrom django.core.files.storage import FileSystemStorage\n# Create your views here.\ndef FileUpload(request):\n if request.method=='POST' and request.FILES['myfile']:\n myfile=request.FILES['myfile']\n fs=FileSystemStorage()\n filename=fs.save(myfile.name,myfile)\n x=fs.url(filename)\n return render(request,'MyApp/welcome.html',{'x':x})\n return render(request,'MyApp/welcome.html')","repo_name":"Rishab260/FullStack_Training_Django_Projects","sub_path":"djDFU/WebApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"36126487012","text":"from django.conf.urls import patterns, url\nfrom keep.collection import views\n\nurlpatterns = patterns('',\n url(r'^$', views.list_archives, name='list-archives'),\n url(r'^new/$', views.edit, name='new'),\n url(r'^new/from-findingaid/$', views.create_from_findingaid,\n name='new-from-findingaid'),\n url(r'^search/$', views.search, name='search'),\n url(r'^suggest/$', views.collection_suggest, name='suggest'),\n url(r'^simple/$', views.simple_browse, name='simple_browse'),\n url(r'^simple/(?P[^/]+)/edit/$', views.simple_edit, name='simple_edit'),\n # NOTE: archive must come after so we don't match named views as archive aliases\n url(r'^(?P[a-z]+)/$', views.browse_archive, name='browse-archive'),\n url(r'^(?P[^/]+)/$', views.view, name='view'),\n url(r'^(?P[^/]+)/playlist.json$', views.playlist, name='playlist'),\n url(r'^(?P[^/]+)/edit/$', views.edit, name='edit'),\n url(r'^(?P[^/]+)/history/$', views.history, name='history'),\n url(r'^(?P[^/]+)/(?P(MODS|RELS-EXT|DC))/$',\n views.view_datastream, name='raw-ds'),\n url(r'^(?P[^/]+)/AUDIT/$', views.view_audit_trail, name='audit-trail'),\n)\n","repo_name":"emory-libraries/TheKeep","sub_path":"keep/collection/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7773147187","text":"from src.profile.common import common_profile\nfrom src.profile.territories.ita import ita_profile\nfrom src.profile.territories.jpn import jpn_profile\n\n\ndef get_all_profile():\n japan = jpn_profile.get_japan_profile()\n italy = ita_profile.get_italy_profile()\n common = common_profile.get_common_profile()\n return f\"{japan} | {italy} | {common}\"\n\n\nif __name__ == '__main__':\n print(get_all_profile())\n","repo_name":"girisagar46/circle-ci-playground","sub_path":"src/profile/get_profile.py","file_name":"get_profile.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10620181317","text":"#coding:utf-8\r\nimport urllib2\r\nimport json\r\nfrom base64 import b64encode as BasicEnc\r\n\r\ndef _post_bug(jira_host, jira_user, bug_info):\r\n\tfull_url = '{0}/rest/api/2/issue/'.format(jira_host)\r\n\tenc_user = BasicEnc(jira_user)\r\n\r\n\tpost_header = {\r\n\t\t'Content-Type': 'application/json',\r\n\t\t'Authorization': 'Basic {0}'.format(enc_user)\r\n\t}\r\n\r\n\tpost_data = json.dumps(bug_info)\r\n\ttry:\r\n\t\treq = urllib2.Request(full_url, data=post_data, headers=post_header)\r\n\t\tresp = urllib2.urlopen(req).read()\r\n\t\treturn resp\r\n\texcept Exception as e:\r\n\t\tmsg = 'post_bug: {0}: {1}'.format(e.__class__.__name__, e)\r\n\t\treturn msg\r\n\r\ndef post_bug(jira_srv, user, bug_info):\r\n\treturn _post_bug(jira_srv, user, bug_info)\r\n\t\r\n\r\n\r\n","repo_name":"guchengcao/sharewithhell","sub_path":"paddy/common/notice/Jira.py","file_name":"Jira.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15054966434","text":"import argparse\nimport json\n\nfrom archimedes.archimedes import Archimedes, logger\n\n\nDASHBOARD_TITLE2ID = {\n \"About\": \"About\",\n \"Affiliations\": \"Affiliations\",\n \"Apache\": \"Apache\",\n \"Askbot\": \"Askbot\",\n \"Bugzilla\": \"Bugzilla\",\n \"Bugzilla Backlog\": \"Bugzilla-Backlog\",\n \"Bugzilla Timing\": \"Bugzilla-Timing\",\n \"Code Complexity\": \"9a00bc60-9900-11e9-82c4-37956b0c932a\",\n \"Code License\": \"07dadc50-9c19-11e9-82c4-37956b0c932a\",\n \"Community Structure by Organization\": \"Community-Structure-by-Organization\",\n \"Community Structure by Project\": \"Community-Structure-by-Project\",\n \"Confluence\": \"Confluence\",\n \"Contributors Growth\": \"4434c9a0-18dd-11e9-ba47-d5cbef43f8d3\",\n \"Data Status\": \"Data-Status\",\n \"Demographics\": \"15e4b020-d075-11e8-8aac-ef7fd4d8cbad\",\n \"Discourse\": \"Discourse\",\n \"Docker\": \"1fe57070-4f11-11ea-ac47-d59b2800ffe6\",\n \"DockerHub\": \"DockerHub\",\n \"Efficiency: Timing overview\": \"69208f40-18cb-11e9-ba47-d5cbef43f8d3\",\n \"Emerging Tech Adoption\": \"EmTech-Adoption\",\n \"Emerging Tech Dev\": \"EmTech-Dev\",\n \"Emerging Tech Social\": \"EmTech-Social\",\n \"EmTech Community Structure\": \"EmTech-Community-Structure\",\n \"Engagement\": \"b7b169e0-14e3-11e9-8aac-ef7fd4d8cbad\",\n \"Functest\": \"Functest\",\n \"Gerrit\": \"Gerrit\",\n \"Gerrit Approvals\": \"95487340-6762-11e9-a198-67126215b112\",\n \"Gerrit Backlog\": \"Gerrit-Backlog\",\n \"Gerrit Efficiency\": \"8c515590-e1de-11e8-8aac-ef7fd4d8cbad\",\n \"Gerrit Timing\": \"Gerrit-Timing\",\n \"Git\": \"Git\",\n \"Git Areas of Code\": \"Git-Areas-of-Code\",\n \"Git Demographics\": \"Git-Demographics\",\n \"Git Pair Programming\": \"Git-Pair-Programming\",\n \"GitHub Development Activity Overview\": \"3f4bf390-b29a-11e8-bbe5-d99a6d067cbc\",\n \"GitHub Events - ClosedEvent\": \"b702de50-83b1-11ea-b68b-31a1aa44b23a\",\n \"GitHub External Contributions\": \"2f1be220-dbb9-11e9-8bb5-a754934c91d5\",\n \"GitHub Issues\": \"GitHub-Issues\",\n \"GitHub Issues Backlog\": \"GitHub-Issues-Backlog\",\n \"GitHub Issues Comments and Collaboration\": \"4b6cdf80-33cd-11ea-b68b-31a1aa44b23a\",\n \"GitHub Issues Comments and Collaboration (with feelings)\": \"a3aa38c0-4f19-11ea-ac47-d59b2800ffe6\",\n \"GitHub Issues Efficiency\": \"c3da5c20-e1c3-11e8-8aac-ef7fd4d8cbad\",\n \"GitHub Issues Timing\": \"GitHub-Issues-Timing\",\n \"GitHub Pull Requests\": \"GitHub-Pull-Requests\",\n \"GitHub Pull Requests Backlog\": \"GitHub-Pull-Requests-Backlog\",\n \"GitHub Pull Requests Comments and Collaboration\": \"bcb51ca0-3870-11ea-b68b-31a1aa44b23a\",\n \"GitHub Pull Requests Efficiency\": \"9663d5a0-e1dc-11e8-8aac-ef7fd4d8cbad\",\n \"GitHub Pull Requests Timing\": \"GitHub-Pull-Requests-Timing\",\n \"GitHub Repositories\": \"8035e0c0-45e6-11e9-b68b-31a1aa44b23a\",\n \"GitLab Issues\": \"2e968fe0-b1bb-11e8-8aac-ef7fd4d8cbad\",\n \"Gitlab Issues Backlog\": \"5e03cfb0-b4f7-11e8-8aac-ef7fd4d8cbad\",\n \"GitLab Issues Efficiency\": \"38fe7980-f6f2-11e8-8aac-ef7fd4d8cbad\",\n \"GitLab Issues Timing\": \"5a542570-b508-11e8-8aac-ef7fd4d8cbad\",\n \"GitLab Merge Requests\": \"b2218fd0-bc11-11e8-8aac-ef7fd4d8cbad\",\n \"GitLab Merge Requests Backlog\": \"078d8780-bcad-11e8-8aac-ef7fd4d8cbad\",\n \"GitLab Merge Requests Efficiency\": \"bff9e0c0-fe16-11e8-8aac-ef7fd4d8cbad\",\n \"GitLab Merge Requests Timing\": \"3eae8110-bc1c-11e8-8aac-ef7fd4d8cbad\",\n \"Gitter\": \"Gitter\",\n \"Google Hits\": \"Google-Hits\",\n \"IRC\": \"IRC\",\n \"Jenkins\": \"Jenkins\",\n \"Jenkins Export (Slow)\": \"Jenkins-Export-(Slow)\",\n \"Jenkins Job Categories\": \"5c707260-2a0f-11e9-b1b8-f3720d7eacea\",\n \"Jenkins Jobs\": \"00862e30-bbf7-11e8-8aac-ef7fd4d8cbad\",\n \"Jenkins Nodes\": \"a41a9940-bcb1-11e8-8aac-ef7fd4d8cbad\",\n \"Jira\": \"Jira\",\n \"Jira Backlog\": \"Jira-Backlog\",\n \"Jira Effort\": \"Jira-Effort\",\n \"Jira Timing\": \"Jira-Timing\",\n \"KIP\": \"KIP\",\n \"Lifecycle\": \"999ea330-f7b2-11e8-865a-85ff6467a442\",\n \"Lines of Code Changed\": \"f13af0e0-18e5-11e9-ba47-d5cbef43f8d3\",\n \"Mailing Lists\": \"MailingLists\",\n \"Maintainer Response to Merge Request Duration\": \"206c9180-1d86-11e9-ba47-d5cbef43f8d3\",\n \"Maniphest\": \"Maniphest\",\n \"Maniphest Backlog\": \"Maniphest-Backlog\",\n \"Maniphest Timing\": \"Maniphest-Timing\",\n \"Mattermost\": \"Mattermost\",\n \"Mediawiki\": \"Mediawiki\",\n \"Meetup\": \"Meetup\",\n \"Meetup Locations\": \"Meetup-Locations\",\n \"Mozilla Club\": \"Mozilla-Club\",\n \"Organization Tracking Overview\": \"2b7c68b0-472f-11ea-97d2-0103fac622e1\",\n \"Organizational Diversity\": \"ab68fe20-17f2-11e9-872f-e17019e68d6d\",\n \"Organizational Diversity by Domains\": \"6e0e2900-18c0-11e9-872f-e17019e68d6d\",\n \"Overall Community Structure\": \"Overall-Community-Structure\",\n \"Overview\": \"Overview\",\n \"Pull Request Merge Duration\": \"00fa7e30-1b0a-11e9-ba47-d5cbef43f8d3\",\n \"Pull Requests Merged\": \"a7b3fd70-ef16-11e8-9be6-c962f0cee9ae\",\n \"Redmine\": \"Redmine\",\n \"Redmine Backlog\": \"Redmine-Backlog\",\n \"Redmine Timing\": \"Redmine-Timing\",\n \"Reps Activities\": \"Reps-Activities\",\n \"Reps Events\": \"Reps-Events\",\n \"RSS\": \"RSS\",\n \"Slack\": \"Slack\",\n \"StackOverflow\": \"Stackoverflow\",\n \"Telegram\": \"Telegram\",\n \"Testing\": \"Testing\",\n \"Twitter\": \"Twitter\"\n}\n\n\ndef import_batch(archimedes, dashboards, by='id', force=False, find=False):\n for title in dashboards:\n dashboard_id = dashboards[title]\n logger.info(\"Importing dashboard %s\" % title)\n try:\n if by == 'id':\n archimedes.import_from_disk(obj_type=\"dashboard\", obj_id=dashboard_id, force=force, find=find)\n else:\n archimedes.import_from_disk(obj_type=\"dashboard\", obj_title=title, force=force, find=find)\n except Exception as ex:\n logger.error(\"Impossible to import dashboard %s, skipping it. %s\" % (dashboard_id, ex))\n continue\n\n\ndef export_batch(archimedes, dashboards, by='id', force=False):\n for title in dashboards:\n dashboard_id = dashboards[title]\n logger.info(\"Exporting dashboard %s\" % title)\n try:\n if by == 'id':\n archimedes.export_to_disk(obj_type=\"dashboard\", obj_id=dashboard_id, force=force)\n else:\n archimedes.export_to_disk(obj_type=\"dashboard\", obj_title=title, force=force)\n except Exception as ex:\n logger.error(\"Impossible to import dashboard %s, skipping it. %s\" % (dashboard_id, ex))\n continue\n\n\ndef get_params():\n parser = argparse.ArgumentParser(usage=\"usage: Euclid [options]\", description=\"Import/Export Kibana dashboards\")\n\n parser.add_argument('url', help='Kibana URL')\n parser.add_argument('root_path', help='Archimedes folder')\n parser.add_argument('--search-by', dest='search_by',\n help='Search dashboards by title or ID', choices=['id', 'title'], default='id')\n parser.add_argument('--dashboards', dest='dashboards',\n help='A dict with a set of dashboards title and id to import', default=None)\n parser.add_argument('--import', dest='import_', action='store_true')\n parser.add_argument('--export', dest='export_', action='store_true')\n parser.add_argument('--all', action='store_true')\n\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n \"\"\"Euclid helps Archimedes to import/export a set of dashboards. They can be passed as a\n JSON file with the following format `{\"dashbord_title-1\": \"dashboard_id-1\", \"dashbord_title-2\": \"dashboard_id-2\"}`.\n If the file isn't defined the dashboards are initialized with the value of DASHBOARD_TITLE2ID. If the option --all\n is defined, all Kibana objects in Archimedes/Kibiter are imported/exported.\n\n A common execution consists of running the export, and the export.\n\n Examples:\n - Import the dashboards from a local Archimedes repo to a Kibana instance\n ./bin/utils http://admin:admin@localhost:5601 /home/dashboards --import --search-by title\n - Import all Kibana objects from a local Archimedes repo to a Kibana instance\n ./bin/utils http://admin:admin@localhost:5601 /home/dashboards --import --all\n - Export the dashboards from a Kibana instance to a local Archimedes repo\n ./bin/utils http://admin:admin@localhost:5601 /home/dashboards --export --dashboards dashboards.json\n - Export all Kibana objects from a Kibana instance to a local Archimedes repo\n ./bin/utils http://admin:admin@localhost:5601 /home/dashboards --export --all\n \"\"\"\n args = get_params()\n\n if (args.import_ and args.export_) or (not args.import_ and not args.export_):\n print(\"One action is needed: select --import or --export\")\n return\n\n archimedes = Archimedes(args.url, args.root_path)\n search_by = args.search_by\n\n if not args.all:\n if args.dashboards:\n with open(args.dashboards, 'r') as f:\n dashboards = json.loads(f.read())\n else:\n dashboards = DASHBOARD_TITLE2ID\n\n if args.import_:\n import_batch(archimedes, dashboards, by=search_by, force=True, find=True)\n\n if args.export_:\n export_batch(archimedes, dashboards, by=search_by, force=True)\n else:\n if args.import_:\n for obj in archimedes.inspect(local=True):\n archimedes.import_from_disk(obj.type, obj.id, obj.title)\n if args.export_:\n for obj in archimedes.inspect(remote=True):\n archimedes.export_to_disk(obj.type, obj.id, obj.title)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Bitergia/archimedes","sub_path":"utils/euclid.py","file_name":"euclid.py","file_ext":"py","file_size_in_byte":9464,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"74155194836","text":"import argparse\nimport random\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\n\ndef my_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--stringy\",\n default=\"The quick brown fox jumps over the lazy dog.\",\n help=\"input string\"\n )\n parser.add_argument(\n \"--pitch\",\n default=\"med\",\n choices=[\"high\", \"med\", \"low\", \"lowest\"],\n help='choose between \"high\", \"med\", \"low\", or \"lowest\"'\n )\n parser.add_argument(\n \"--rnd_factor\",\n type=float,\n help=\"random factor\"\n )\n parser.add_argument(\n \"--uniform_sample_rate\",\n type=float,\n default=44100,\n help=\"uniform sample rate\"\n )\n\n return parser.parse_args()\n\n\ndef main():\n # Get arguments.\n argument = my_parser()\n\n stringy = argument.stringy.lower()\n sounds = {}\n keys = [\n \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\",\n \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\",\n \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"th\", \"sh\", \" \", \".\"\n ]\n for index, ltr in enumerate(keys):\n num = index + 1\n if num < 10:\n num = \"0\" + str(num)\n sounds[ltr] = (\n \"./sounds/\" +\n argument.pitch +\n \"/sound\" +\n str(num) +\n \".wav\"\n )\n\n if argument.rnd_factor is None:\n if argument.pitch == \"med\":\n rnd_factor = .35\n else:\n rnd_factor = .25\n else:\n rnd_factor = argument.rnd_factor\n\n infiles = []\n\n for i, char in enumerate(stringy):\n if char == \"s\" and stringy[i+1] == \"h\": # test for \"sh\" sound\n infiles.append(sounds[\"sh\"])\n elif char == \"t\" and stringy[i+1] == \"h\": # test for \"th\" sound\n infiles.append(sounds[\"th\"])\n # test if previous letter was \"s\" or \"s\" and current letter is \"h\"\n elif char == \"h\" and (stringy[i-1] == \"s\" or stringy[i-1] == \"t\"):\n pass\n elif char == \",\" or char == \"?\":\n infiles.append(sounds[\".\"])\n elif char == stringy[i-1]: # skip repeat letters\n pass\n # skip characters that are not letters or periods.\n elif char.isalpha() or char == \".\":\n infiles.append(sounds[char])\n # skip characters that are not letters or periods.\n else:\n pass\n\n combined_sounds = None\n\n print(\"Length of text is\", len(infiles))\n for index, sound in enumerate(infiles):\n tempsound = AudioSegment.from_wav(sound)\n if stringy[len(stringy)-1] == \"?\":\n if index >= len(infiles)*.8:\n # shift the pitch up by half an octave\n # speed will increase proportionally\n octaves = random.random() * rnd_factor + (index-index*.8) * .1 + 2.1\n else:\n octaves = random.random() * rnd_factor + 2.0\n else:\n # shift the pitch up by half an octave\n # speed will increase proportionally\n octaves = random.random() * rnd_factor + 2.3\n new_sample_rate = int(tempsound.frame_rate * (2.0 ** octaves))\n new_sound = tempsound._spawn(\n tempsound.raw_data,\n overrides={\"frame_rate\": new_sample_rate}\n )\n # set uniform sample rate\n new_sound = new_sound.set_frame_rate(argument.uniform_sample_rate)\n if combined_sounds:\n combined_sounds = combined_sounds + new_sound\n else:\n combined_sounds = new_sound\n\n combined_sounds.export(\"./sound.wav\", format=\"wav\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"andy5343927/animalese-generator","sub_path":"my_animalese.py","file_name":"my_animalese.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"36326402531","text":"import torch\nfrom time import time as GETTIME\nimport torch.nn.functional as F\nfrom tqdm import tqdm\nimport numpy as np\n\nfrom sklearn.metrics import explained_variance_score, roc_auc_score, average_precision_score, precision_recall_curve, auc\nfrom sklearn.metrics import precision_score, recall_score\nfrom scipy.stats import spearmanr\nfrom tslearn.metrics import dtw_path\n\ndef faithfulness(model, X, time, y, pert_method, samples = 30):\n\n model.eval()\n reg_out = model(X, time).softmax()\n sum_faith = 0\n\n for s in samples:\n\n # Try to make perturbations until\n bad_pert = True\n while bad_pert:\n Xpert = pert_method(X)\n pert_out = model(Xpert, time).softmax()\n # check criteria\n criteria = (pert_out.argmax() == reg_out.argmax())\n bad_pert = not criteria # Bad perturbation if criteria does not hold\n \n sum_faith += F.kl_div(reg_out, pert_out).item()\n\n\n return (1 / samples) * sum_faith \n\ndef similarity_faithfulness(model, test_X, test_time, explainer = None, explist = None, samples = 50):\n '''\n Measure faithfulness based on similarities of linear correlations\n between differences in 1) model prediction and 2) explanations\n\n - Use Dynamic Time Warping (DTW) for explanations\n - Use KL divergence for predictions\n\n If using explist feature, must provide testX, test_time that corresponds with indices in explist\n '''\n\n model.eval()\n\n # Sample pairs of samples\n if explainer is not None:\n inds = torch.arange(test_X.shape[1])\n else: # Use list\n inds = torch.arange(len(explist))\n\n combs = torch.combinations(inds)\n combs = combs[ torch.randperm(combs.shape[0])[:samples] ]\n\n exp_scores, pred_scores = [], []\n\n for i, j in tqdm(combs):\n\n predi = model(test_X[:,i,:], test_time[:,i].unsqueeze(dim=1))\n predj = model(test_X[:,j,:], test_time[:,j].unsqueeze(dim=1))\n\n # Get explanation for both:\n\n yi = predi.softmax(dim=1).argmax(dim=1) # Use computed y values (don't care about correctness)\n yj = predj.softmax(dim=1).argmax(dim=1)\n\n if explainer is not None:\n expi = explainer(model, test_X[:,i,:], test_time[:,i].unsqueeze(dim=1), y = yi).detach().clone().cpu().numpy()\n expj = explainer(model, test_X[:,j,:], test_time[:,j].unsqueeze(dim=1), y = yj).detach().clone().cpu().numpy()\n else: # Skip running the explainer, directly extract from tester\n expi = explist[int(i)]\n expj = explist[int(j)]\n\n cur = GETTIME()\n _, exp_sim = dtw_path(expi, expj)\n exp_scores.append(exp_sim)\n #exp_sim = torch.norm((expi - expj).flatten(), p = 2).item()\n\n predi, predj = F.log_softmax(predi, dim=1), F.log_softmax(predj, dim=1)\n\n pred_sim = F.kl_div(predi, predj, reduction = 'batchmean', log_target = True)\n pred_scores.append(pred_sim.item())\n\n print('Exp scores', exp_scores)\n print('Pred scores', pred_scores)\n cor, _ = spearmanr(exp_scores, pred_scores)\n\n return cor\n\ndef faithfulness_violation(model, X, times, mask_X, mask_times, y):\n '''\n Metric based on Faithfulness Violation presented in Liu et al., ICML 2022 \n (https://arxiv.org/pdf/2201.12114.pdf)\n - Don't use the violation part, only the change in confidence of label\n Params:\n model: Must only return prediction, no attention values, during forward call\n mask_X: \n mask_times: \n '''\n\n fullpred = model(X, times)\n maskpred = model(mask_X, mask_times)\n\n yind = y.int()\n # Must mask the \n C = fullpred[0,yind] - maskpred[0,yind]\n\n return C\n\ndef normalize_exp(exps):\n norm_exps = torch.empty_like(exps)\n for i in range(exps.shape[1]):\n norm_exps[:,i,:] = (exps[:,i,:] - exps[:,i,:].min()) / (exps[:,i,:].max() - exps[:,i,:].min() + 1e-9)\n return norm_exps\n\ndef normalize_one_exp(exps):\n norm_exps = (exps - exps.min()) / (exps.max() - exps.min() + 1e-9)\n return norm_exps\n\ndef ground_truth_xai_eval(generated_exps, gt_exps, penalize_negatives = True, times = None):\n '''\n Compute auprc of generated explanation against ground-truth explanation\n - auprc is computed across one sample, averaged across all samples\n\n NOTE: Assumes all explanations have batch-first style, i.e. (B,T,d) - captum input/output\n\n Params:\n generated_exps: Explanations generated by method under evaluation\n gt_exps: Ground-truth explanations on which to evaluate\n '''\n\n # Normalize generated explanation:\n generated_exps = normalize_exp(generated_exps).detach().clone().cpu().numpy()\n gt_exps = gt_exps.detach().clone().cpu().numpy()\n gt_exps = gt_exps.astype(int)\n\n all_auprc, all_aup, all_aur = [], [], []\n for i in range(generated_exps.shape[1]):\n #auprc = roc_auc_score(gt_exps[i].flatten(), generated_exps[i].flatten())\n # print('gt exps', gt_exps[:,i,:].flatten().shape)\n # print('gen', generated_exps[:,i,:].flatten())\n if times is not None:\n gte = (gt_exps[:,i,:][times[:,i] > -1e5]).flatten()\n gene = normalize_one_exp(generated_exps[:,i,:][times[:,i] > -1e5]).flatten()\n auprc = average_precision_score(gte, gene)\n prec, rec, thres = precision_recall_curve(gte, gene)\n else:\n auprc = average_precision_score(gt_exps[:,i,:].flatten(), generated_exps[:,i,:].flatten())\n prec, rec, thres = precision_recall_curve(gt_exps[:,i,:].flatten(), generated_exps[:,i,:].flatten())\n aur = auc(thres, rec[:-1]) # Last value in recall curve is always 0 (see sklearn documentation)\n aup = auc(thres, prec[:-1]) # Last value in precision curve is always 1 (see sklearn documentation)\n all_auprc.append(auprc)\n all_aup.append(aup)\n all_aur.append(aur)\n\n output_dict = {\n 'auprc': all_auprc,\n 'aup': all_aup,\n 'aur': all_aur\n }\n\n return output_dict\n\ndef jaccard_similarity(tensor1, tensor2):\n # From ChatGPT\n intersection = torch.sum(tensor1 * tensor2)\n union = torch.sum(torch.max(tensor1, tensor2)) # Use max for element-wise OR\n \n jaccard = intersection / union\n \n return jaccard.item()\n\ndef ground_truth_IoU(generated_exps, gt_exps, threshold = 0.9):\n '''\n Compute auprc of generated explanation against ground-truth explanation\n - auprc is computed across one sample, averaged across all samples\n\n NOTE: Assumes all explanations have batch-first style, i.e. (B,T,d) - captum input/output\n\n Params:\n generated_exps: Explanations generated by method under evaluation\n gt_exps: Ground-truth explanations on which to evaluate\n '''\n\n # Normalize generated explanation:\n generated_exps = normalize_exp(generated_exps).detach().clone().cpu()\n gt_exps = gt_exps.detach().clone().cpu().float()\n #gt_exps = gt_exps.astype(int)\n\n all_iou = []\n for i in range(generated_exps.shape[1]):\n #auprc = roc_auc_score(gt_exps[i].flatten(), generated_exps[i].flatten())\n # print('gt exps', gt_exps[:,i,:].flatten().shape)\n # print('gen', generated_exps[:,i,:].flatten())\n gen = generated_exps[:,i,:].flatten()\n thresh = torch.quantile(gen, threshold)\n generated_e = torch.where(gen >= thresh, 1.0, 0.0).float()\n iou = jaccard_similarity(generated_e, gt_exps[:,i,:].flatten())\n all_iou.append(iou)\n\n output_dict = {\n 'iou': all_iou,\n }\n\n return output_dict\n\ndef ground_truth_precision_recall(generated_exps, gt_exps, num_points = 50):\n '''\n Compute AUROC of generated explanation against ground-truth explanation\n - AUROC is computed across one sample, averaged across all samples\n\n NOTE: Assumes all explanations have batch-first style, i.e. (B,T,d) - captum input/output\n\n Params:\n generated_exps: Explanations generated by method under evaluation\n gt_exps: Ground-truth explanations on which to evaluate\n '''\n\n # Normalize generated explanation:\n generated_exps = normalize_exp(generated_exps).detach().clone().cpu().numpy()\n gt_exps = gt_exps.detach().clone().cpu().numpy().astype(int)\n\n thresholds = np.linspace(0,1,num_points)\n if num_points == 1:\n # Support for evaluating on masks\n thresholds = [0.5]\n\n total_prec, total_rec, masked_in = [], [], []\n\n for i in range(generated_exps.shape[0]):\n \n best_prec, best_rec, best_masked_in = -1, -1, -1\n\n # Try different thresholds for discretizing masks\n for t in thresholds:\n genexp = (generated_exps[i].flatten() > t).astype(int)\n prec = precision_score(gt_exps[i].flatten(), genexp)\n recall = recall_score(gt_exps[i].flatten(), genexp)\n\n # Determine if we have the best precision score:\n if best_prec < prec:\n best_prec = prec\n best_rec = recall\n best_masked_in = genexp.sum()\n\n total_prec.append(best_prec)\n total_rec.append(best_rec)\n masked_in.append(best_masked_in)\n\n return total_prec, total_rec, masked_in\n\ndef connected_component_count(exps):\n count = np.zeros(exps.shape[0])\n for i in range(exps.shape[0]): # Iterate over samples\n for j in range(exps.shape[2]): # Iterate over sensors\n on_bool = False\n for k in range(exps.shape[1]): # Iterate over sensors:\n if exps[i,k,j] == 0:\n if on_bool: # If we hit a flip in the sensor reading\n count[i] += 1\n on_bool = False\n # Nothing if we're already on False\n else:\n on_bool = True # If we're now at 1, flip to True \n\n else:\n if on_bool: # Upcount if we ended on on_bool\n count[i] += 1\n\n return count # Should be length of samples\n\ndef count_time_sensor_sparsity(exps):\n '''\n Counts sparsity with respect to time points and sensors\n '''\n # Time first:\n timepts = exps.sum(dim=2)\n time_sparse = (timepts > 0).sum(dim=1) # Should be size of number of samples\n\n sensors = exps.sum(dim=1)\n sensor_sparse = (sensors > 0).sum(dim=1) # Should be size of number of samples\n\n return time_sparse.detach().clone().cpu().numpy(), sensor_sparse.detach().clone().cpu().numpy()\n\nif __name__ == '__main__':\n # Test out connected components:\n a = torch.zeros(1, 50, 4)\n a[0,3:6,1] = 1\n a[0,4:9,2] = 1\n print(a)\n c = count_time_sensor_sparsity(a)\n print(c)","repo_name":"mims-harvard/TimeX","sub_path":"txai/utils/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":10613,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"85"} +{"seq_id":"5717648325","text":"import json\nimport sys\n\nfrom analyzers.MiniLeagueAnalyzer import MiniLeagueAnalyzer\nfrom read_input import read_input\n\n\"\"\"\n* Author: @Georgi Arnaudov \n* Twitter: @FPL_arndff\n\"\"\"\n\n\ndef read_league_data():\n league_name = input(\"Enter league name: \")\n league_id = read_input(\"Enter league id: \")\n\n result = (league_name, league_id)\n return result\n\n\ndef load_config(key):\n person = key.split(\"-\")[1]\n\n with open(\"config/mini_league_analyzer_config.json\", \"r\") as read_file:\n all_data = json.load(read_file)\n\n main_dir = all_data.get(\"main_dir\", \"\")\n save_dir = \"{}/{}\".format(main_dir, person)\n\n data = all_data.get(person, \"\")\n ids_file = data.get(\"ids_file\", \"\")\n league_name = data.get(\"league_name\", \"\")\n league_id = data.get(\"league_id\", -1)\n\n result = (ids_file, save_dir, league_name, league_id)\n return result\n\n\ndef create_analyzer_objects(key):\n (ids_file, save_dir, league_name, league_id) = load_config(key)\n analyzers = []\n\n if ids_file != \"\":\n analyzers.append(MiniLeagueAnalyzer(ids_file=ids_file, save_dir=save_dir))\n if league_id != -1:\n analyzers.append(MiniLeagueAnalyzer(ids_file=\"\",\n save_dir=save_dir,\n league_name=league_name,\n league_id=league_id))\n\n return analyzers\n\n\ndef execute():\n if len(sys.argv) == 2 and sys.argv[1].startswith(\"config-\"):\n analyzers = create_analyzer_objects(sys.argv[1])\n [mini_league_analyzer.write_data_to_csv() for mini_league_analyzer in analyzers]\n else:\n if len(sys.argv) == 2:\n mini_league_analyzer = MiniLeagueAnalyzer(ids_file=sys.argv[1])\n elif len(sys.argv) == 3:\n mini_league_analyzer = MiniLeagueAnalyzer(ids_file=sys.argv[1], save_dir=sys.argv[2])\n else:\n (league_name, league_id) = read_league_data()\n mini_league_analyzer = MiniLeagueAnalyzer(ids_file=\"\",\n save_dir=\"\",\n league_name=league_name,\n league_id=league_id)\n\n mini_league_analyzer.write_data_to_csv()\n\n\ndef main():\n execute()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"arndff/fpl-rivals-tracker","sub_path":"mini_league_main.py","file_name":"mini_league_main.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"17161476010","text":"from collections import deque\n\n# [\"최소 필요 피로도\", \"소모 피로도\"]\n\nm = -1\n\n\ndef solution(k, dungeons):\n global m\n visited = [False for i in range(len(dungeons))]\n\n def dfs(cnt, cur_k, k, visited, dungeons): # cnt : count | cur_k : 피로도 잔량\n global m\n f = True\n for idx, i in enumerate(dungeons):\n if visited[idx] == False and cur_k >= i[0]:\n visited[idx] = True\n dfs(cnt+1, cur_k-i[1], k, visited, dungeons)\n visited[idx] = False\n f = False\n if f:\n m = max(m, cnt)\n\n dfs(0, k, k, visited, dungeons)\n if m == 0:\n return -1\n return m\n\n\nprint(solution(80, [[80, 20], [50, 40], [30, 10]]))\n","repo_name":"ghkdqhrbals/algorithm","sub_path":"(GREEDY)피로도.py","file_name":"(GREEDY)피로도.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30104494397","text":"from random import randint\nfrom typing import Any, List\n\n\ndef chop(list: List[Any]) -> None:\n \"\"\"This honestly feels really wrong in Python to edit a list in a function by\n reference instead of returning a new list.\"\"\"\n del list[0]\n del list[-1]\n return None\n\n\ndef middle(list: List[Any]) -> List[Any]:\n \"\"\"This feels more natural in Python to return a new list instead of editing\n the original list in place.\"\"\"\n if randint(0, 10) == 0:\n print(\"Your list is now mid.\")\n return list[1:-1]\n\n\nif __name__ == \"__main__\":\n t = [1, 2, 3, 4]\n print(t)\n chop(t)\n print(t)\n t = [1, 2, 3, 4, 5] # Add an extra element to test the middle function\n print(middle(t))\n","repo_name":"AetherBreaker/CIS-104","sub_path":"Module8/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7568709957","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 25 09:55:13 2018\n\n@author: Pshypher\n\"\"\"\n\n###########################################################################\n## Class Time\n###########################################################################\n\nclass Time(object):\n \n def __init__(self,hours=0,minutes=0,seconds=0):\n \"\"\"Construct a Time using three integer variables.\"\"\"\n for param in (hours,minutes,seconds):\n if not isinstance(param, int):\n self.__second,self.__minute,self.__hour = 0,0,0\n break\n else:\n self.__second = seconds % 60\n minutes = seconds//60 + minutes\n self.__minute = minutes % 60\n hours = minutes//60 + hours\n self.__hour = hours % 24\n \n def __str__(self):\n \"\"\"String representation of the Time instance.\"\"\"\n return \"({:02d}:{:02d}:{:02d})\".format(self.__hour,self.__minute,\n self.__second)\n \n def __repr__(self):\n \"\"\"Time instance output in the Python shell.\"\"\"\n # uses the Time.__str__(self) method\n return \"Class Time \" + self.__str__()\n \n def from_str(self, time_str):\n \"\"\"Updates the Time using the time_str in the format \"hh:mm:ss\".\"\"\"\n hour,minutes,seconds = time_str.split(':')\n self.__hour = int(hour.strip())\n self.__minute = int(minutes.strip())\n self.__second = int(seconds.strip())\n \n def __add__(self, param):\n \"\"\"Adds two Time instances or a Time instance and an integer \n together. Returns a new Time instance.\"\"\"\n if isinstance(param, int):\n param = Time(param,0,0)\n if isinstance(param, Time):\n hours = self.__hour + param.__hour\n minutes = self.__minute + param.__minute\n seconds = self.__second + param.__second\n return Time(hours,minutes,seconds)\n else:\n raise(TypeError)\n \n def __radd__(self,param):\n \"\"\"Adds a Time instance and an integer together (in reverse). Returns\n a Time instance.\"\"\"\n return self.__add__(param)","repo_name":"Pshypher/tpocup","sub_path":"ch11/labs/clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29082450416","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom numpy import ndarray\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.decomposition import PCA\nfrom typing import List\n\n\nclass ClusterFeatures(object):\n\n def __init__(\n self,\n features: ndarray,\n algorithm: str = 'kmeans',\n pca_k: int = None,\n random_state: int = 12345\n ):\n \"\"\"\n :param features: input features\n :param algorithm: algorithm to cluster (default: kmeans)\n :param pca_k: reduce number of dimensions by PCA or not\n :param random_state: random state for algorithm\n \"\"\"\n if pca_k:\n self.features = PCA(n_components=pca_k).fit_transform(features)\n else:\n self.features = features\n\n self.algorithm = algorithm\n self.pca_k = pca_k\n self.random_state = random_state\n\n def __get_model(self, k: int):\n \"\"\" Function to get clustering model\n :param k: number of clusters\n :returns: KMeans model with parameters\n \"\"\"\n if self.algorithm == 'gmm':\n return GaussianMixture(n_components=k, random_state=self.random_state)\n return KMeans(n_clusters=k, random_state=self.random_state)\n\n def __get_centroids(self, model):\n \"\"\" Function to get center point of a cluster\n :param model: clustering model\n :returns: center point value of a cluster\n \"\"\"\n if self.algorithm == 'gmm':\n return model.means_\n return model.cluster_centers_\n\n def __find_closest_args(self, centroids: np.ndarray):\n \"\"\" Function to get center sentence of a cluster\n :param centroids: center point of cluster\n :returns: Center sentence with the most important meaning of paragraph\n \"\"\"\n centroid_min = 1e10\n cur_arg = -1\n args = {}\n used_idx = []\n\n for j, centroid in enumerate(centroids):\n\n for i, feature in enumerate(self.features):\n value = np.linalg.norm(feature - centroid)\n\n if value < centroid_min and i not in used_idx:\n cur_arg = i\n centroid_min = value\n\n used_idx.append(cur_arg)\n args[j] = cur_arg\n centroid_min = 1e10\n cur_arg = -1\n\n return args\n\n def cluster(self, ratio: float = 0.1, no_words: int = 0, max_words: int = 40) -> List[int]:\n \"\"\" Function to apply clustring model to document\n :param ratio: ratio for summarization\n :param no_words: number of valid words in document\n :param max_words: maximum number of words in summarized doc.\n :returns: Summarized document\n \"\"\"\n if max_words != -1:\n if ratio * no_words > max_words:\n ratio = max_words / no_words\n k = 3 if ratio * \\\n len(self.features) < 3 else int(len(self.features) * ratio)\n k = min(k, len(self.features))\n k = min(k, 8)\n model = self.__get_model(k).fit(self.features)\n centroids = self.__get_centroids(model)\n cluster_args = self.__find_closest_args(centroids)\n sorted_values = sorted(cluster_args.values())\n return sorted_values\n\n def __call__(self, ratio: float = 0.1) -> List[int]:\n return self.cluster(ratio)\n","repo_name":"phanxuanphucnd/text-summarization-system","sub_path":"summarizer/ClusterFeatures.py","file_name":"ClusterFeatures.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"24913076676","text":"import os\nimport sys\nimport datetime\nimport random\nsys.path.append('..')\nsys.path.append('../dao')\nimport lc_service\nfrom dao.account_info_dao import DaoAccountInfo\nfrom dao.daily_info_dao import DaoDailyInfo\nfrom dao.dao import Dao\nfrom email_service import EmailService\n\n\ndef open_user_lc_game(user, status):\n leetcode_service = lc_service.LeetcodeService()\n dao_daily = DaoDailyInfo()\n dao_account = DaoAccountInfo()\n # 重新设置用户账户的基本信息,coins,medal,status\n acc_info = dao_account.search_account(user)\n his_coins = acc_info.coins\n his_medal = acc_info.medal\n\n medal = leetcode_service.get_user_medal_info(user)\n # coins = 100\n if medal == 1 and (mdeal & his_medal) == 0:\n his_coins += 30\n if medal == 2 and ((medal & his_medal) == 0):\n medal = 3\n his_medal += 50\n dao_account.update_user_coins(user, his_coins)\n dao_account.update_user_medal(user, medal)\n dao_account.update_account_status(user, status)\n # 更新用户每日统计信息\n td = str(datetime.date.today())\n user_daily_info = dao_daily.serach_single_user_daily_info(\n user, td) # 查看今天用户是否存在\n score = leetcode_service.get_user_score_info(user)\n info = leetcode_service.get_user_lc_stat_info(user)\n info.rating_score = score\n info.date_time = td\n # print(info.as_dict())\n if not user_daily_info:\n dao_daily.add_single_user_daily_info(info)\n else:\n dao_daily.update_single_user_daily_info(info)\n\n\ndef random_char():\n chars = \"abcdefghigklmnopqrstuvwxyz\"\n k = random.randint(0, 25)\n return chars[k]\n\n\ndef generate_user_token():\n dao_account = DaoAccountInfo()\n user_infos = dao_account.load_all_account_infos()\n for user, item in user_infos.items():\n token = ''\n for i in range(0, 8):\n token += random_char()\n dao_account.update_user_token(user, token)\n\n\ndef send_award(user):\n dao_acc = DaoAccountInfo()\n \n award_str = \"\"\"恭喜您在网站积分排名中名列前矛,感谢对网站的认可和贡献,同时也表示鼓励 \\\n 有一份小礼物要送给您,辛苦填写一下快递地址,收件人信息和电话号码~ \\\n 回复此邮件即可!!\\n 请放心,所有信息会严格保密。\"\"\"\n award_str = \"\"\"恭喜您完成UNBELIEVABLE难度目标,实现自我突破。感谢对网站的认可和贡献,同时也表示鼓励 \\\n 有一份小礼物要送给您,辛苦填写一下快递地址,收件人信息和电话号码~ \\\n 回复此邮件即可!!\\n 请放心,所有信息会严格保密。\"\"\"\n user_info = dao_acc.search_account(user)\n if user_info.email != '':\n print(user_info.email, award_str)\n EmailService.send_email(user_info.email, award_str)\n\nuser = 'train_sky'\nopen_user_lc_game(user, 0)\n","repo_name":"qscool1987/leetcode","sub_path":"tools/lc_notify/scripts/user_limit_op.py","file_name":"user_limit_op.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"85"} +{"seq_id":"41144687393","text":"import cv2\n\nvideo_name = \"raw_data/Neovision2-Training-Heli-002.mpg\"\n\n'''Extracting frames from a video'''\ncap = cv2.VideoCapture(video_name)\nprint(cap)\nsuccess,image = cap.read()\ncount = 0\nsuccess = True\nwhile success:\n success,image = cap.read()\n cv2.imwrite(\"test_frames/frame%d.jpg\" % count, image) # save frame as JPEG file\n if cv2.waitKey(10) == 27: # exit if Escape is hit\n break\n count += 1\ncap.release()\n","repo_name":"aleksod/Main_Repo","sub_path":"Projects/HeliTrack/other/frame_extraction.py","file_name":"frame_extraction.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"35005566703","text":"## install python3 ##\n#python3 -m pip install --upgrade pip\n#python3 -m pip install --upgrade telethon\n#python3 -m pip install tqdm\n\n## Links\n# https://tl.telethon.dev/methods/channels/get_full_channel.html\n# https://core.telegram.org/methods\n\nimport re\nimport gdown\nfrom telethon.sync import TelegramClient\nfrom telethon.tl.functions.messages import GetDialogsRequest\nfrom telethon.tl.functions.channels import GetFullChannelRequest\nfrom telethon.tl.types import InputPeerEmpty\nfrom tqdm import tqdm\n\napi_id = 25625372 # Your API ID\napi_hash = 'f156d103def33a79bf838c8b9afa7e1f' # Your API HASH\n\n\n# def download_media(group, cl, name):\n# messages = cl.get_messages(group, limit=2000)\n\n# for message in tqdm(messages):\n# message.download_media('./' + name + '/')\n\n\nwith TelegramClient('name', api_id, api_hash) as client:\n ## check login start ##\n # client.send_message('me','Hello, myself')\n # print(client.download_profile_photo('me'))\n ## check login end ##\n\n result = client(GetDialogsRequest(\n offset_date=None,\n offset_id=0,\n # offset_peer=InputPeerEmpty(),\n offset_peer='username',\n limit=500,\n hash=0,\n ))\n\n # title = 'RkyGroupTest1' # Title for group chat\n # for chat in result.chats:\n # print(chat)\n\n # if chat.title == title:\n # messages = client.get_messages(chat,limit=2000)\n # for message in tqdm(messages):\n # # print(message)\n # message.download_media('./' + title + './')\n # # download_media(chat, client, title)\n\n title = 'Prashant Tiwari' # Title for group chat\n for chat in result.chats:\n # print(chat)\n\n if chat.title == title:\n messages = client.get_messages(chat,limit=10)\n for message in tqdm(messages):\n print(message.date)\n print(message.message)\n url = re.search(\"(?Phttps?://drive[^\\s]+)\", str(message.message))\n print(url)\n output = './'\n url = \"https://drive.google.com/file/d/1qy10dGIK35t-yB3HlgYCNwrLjyLDkJ50/view\"\n gdown.download(url, output, quiet=False)\n # message.download_media('./' + title + './')\n # download_media(chat, client, title)\n\n # title = 'RkyGroupTest1' # Title for channel\n # channel = client(GetFullChannelRequest(title))\n # print(channel.full_chat)\n\n # messages = client.get_messages(channel.full_chat,limit=2000)\n\n # for message in tqdm(messages):\n # message.download_media('./' + title + './')\n\n # download_media(channel.full_chat, client, title)","repo_name":"RKY2023/Projects","sub_path":"Telegram File Organiser/Tel.py","file_name":"Tel.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38190451478","text":"dr = [1, -1, 0, 0]\ndc = [0, 0, -1, 1]\nmovimientos = ['D', 'U', 'L', 'R']\n\n# Busqueda en anchura (BFS)\nvisited = [] # nodos visitaods\nqueue = [] # cola\n\ndef bfs(grid, start, end):\n visited.append(start)\n queue.append((start, \"\"))\n idx = 0 # indice del elemento.\n while queue:\n (x, y), ruta = queue[idx]\n if (x, y) == end:\n return \"SÍ\\n\" + str(len(ruta)) + \"\\n\" + ruta\n\n for i, j, letra in zip(dr, dc, movimientos):\n r2, c2 = x + i, y + j\n if 0 <= r2 < n and 0 <= c2 < m and grid[r2][c2] != '#' and (r2, c2) not in visited:\n queue.append(((r2, c2), ruta + letra))\n visited.append((r2, c2))\n idx += 1\n return \"NO\"\n\n\n\nn, m = map(int, input().split())\ngrid = [list(input()) for _ in range(n)]\n\n\na, b = None, None\n\nfor i in range(n):\n for j in range(m):\n if grid[i][j] == 'A':\n a = (i, j)\n elif grid[i][j] == 'B':\n b = (i, j)\n\nprint(bfs(grid, a, b))\n","repo_name":"mgonzalz/eda2_grafos","sub_path":"ejercicio02.py","file_name":"ejercicio02.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10382482327","text":"from tkinter import *\nfrom threading import Thread\nimport time\nimport random\n\n\ndef pressed(event):\n global moveDirection, isPause, isMoveDirectionCanChange\n\n key = event.keysym.lower() if event.char == ' ' else event.char.lower()\n\n if isPause and key == 'space':\n isPause = False\n elif not isPause and key == 'space':\n isPause = True\n\n if isMoveDirectionCanChange:\n if moveDirection in list(Directions)[:2] and key in list(Directions)[2:]:\n moveDirection = key\n isMoveDirectionCanChange = False\n elif moveDirection in list(Directions)[2:] and key in list(Directions)[:2]:\n moveDirection = key\n isMoveDirectionCanChange = False\n\n\ndef GenerateSnake(root, snake_map, snake):\n global moveDirection\n\n moveDirection = list(Directions)[random.randint(0, 3)]\n\n x = random.randint(3, len(snake_map) - 3)\n y = random.randint(3, len(snake_map[0]) - 3)\n\n snake_map[x][y] = 1\n snake_position = [x, y]\n snake.append(snake_position.copy())\n\n UpdatePosition(root, snake_position, map_colors.get('1'))\n\n\ndef Generate(root, snake_map, generate_type):\n x = random.randint(0, len(snake_map) - 1)\n y = random.randint(0, len(snake_map[0]) - 1)\n\n while snake_map[x][y] != 0:\n x = random.randint(0, len(snake_map) - 1)\n y = random.randint(0, len(snake_map[0]) - 1)\n\n snake_map[x][y] = generate_type\n position = [x, y]\n\n UpdatePosition(root, position, map_colors.get(str(generate_type)))\n\n\ndef SnakeMove(root, snake_map, snake, apples):\n global isAlive, isPause, isMoveDirectionCanChange\n\n isApple = False\n while isAlive:\n while isPause:\n pass\n\n time.sleep(0.1)\n\n snakeX, snakeY = snake[0][0], snake[0][1]\n\n snake_map[snakeX][snakeY] = 0\n prev_pos = [snakeX, snakeY]\n\n if moveDirection in list(Directions)[:2]:\n snakeY += eval(Directions.get(moveDirection))\n elif moveDirection in list(Directions)[2:]:\n snakeX += eval(Directions.get(moveDirection))\n\n if snakeX == len(snake_map) or snakeY == len(snake_map[0]) or snakeX == -1 or snakeY == -1:\n print('GAME OVER')\n isAlive = False\n break\n\n if snake_map[snakeX][snakeY] == -2:\n apples += 1\n root.title(f'Яблок собрано: {apples}')\n Generate(root, snake_map, -2)\n\n snake.insert(1, prev_pos)\n isApple = True\n\n if snake_map[snakeX][snakeY] == -1 or snake_map[snakeX][snakeY] == 2:\n print('GAME OVER')\n isAlive = False\n break\n\n snake_map[snakeX][snakeY] = 1\n snake[0] = [snakeX, snakeY]\n\n if len(snake) == 1:\n snake.append(prev_pos.copy())\n elif len(snake) == 2:\n snake[-1] = prev_pos.copy()\n\n if not isApple and len(snake) > 2:\n snake[1], snake[2:] = prev_pos, snake[1:-1]\n\n for i in snake:\n if i == snake[0]:\n UpdatePosition(root, i, map_colors.get('1'))\n snake_map[i[0]][i[1]] = 1\n elif len(snake) > 1 and i != snake[-1]:\n UpdatePosition(root, i, map_colors.get('2'))\n snake_map[i[0]][i[1]] = 2\n elif i == snake[-1]:\n UpdatePosition(root, i, map_colors.get('0'))\n snake_map[i[0]][i[1]] = 0\n\n isApple = False\n isMoveDirectionCanChange = True\n root.destroy()\n\n\ndef UpdatePosition(root, position, color, prev_pos=None, prev_pos_color=None):\n if prev_pos is not None or prev_pos_color is not None:\n root.children[f'({prev_pos[0]}:{prev_pos[1]})'].configure(bg=prev_pos_color)\n root.children[f'({position[0]}:{position[1]})'].configure(bg=color)\n\n\ndef Initialisation(root, snake_map, snake, apples, wall_count):\n root.attributes('-fullscreen', True)\n root.bind(\"\", pressed)\n root.title(f'Яблок собрано: {apples}')\n\n UpdateMap(snake_map)\n\n Generate(root, snake_map, -2)\n GenerateSnake(root, snake_map, snake)\n\n for _ in range(wall_count):\n Generate(root, snake_map, -1)\n\n snake_move_thread = Thread(target=SnakeMove, args=(root, snake_map, snake, apples))\n snake_move_thread.start()\n\n\ndef UpdateMap(snake_map):\n for i in range(len(snake_map)):\n for j in range(len(snake_map[i])):\n color = map_colors.get(str(snake_map[i][j]))\n\n btn = Button(bd=0, name=f\"({i}:{j})\", bg=color, width=2, height=1, state=DISABLED) # bd=0 убирает края\n btn.grid(row=i, column=j)\n\n\ndef Snake(map_width, map_height, wall_count):\n root = Tk()\n\n apples, snake = 0, []\n snake_map = [[0 for _ in range(map_width)] for _ in range(map_height)]\n\n Initialisation(root, snake_map, snake, apples, wall_count)\n root.mainloop()\n\n\nDirections = {'d': '+ 1',\n 'a': '- 1',\n 's': '+ 1',\n 'w': '- 1'}\nmoveDirection = ''\n\nisMoveDirectionCanChange = isPause = isAlive = True\n\nif __name__ == '__main__':\n WIDTH = 40\n HEIGHT = 20\n\n APPLE = 'FF0000'\n WALL = 'FFFFFF'\n GRASS = '00AA00'\n SNAKE = '000000'\n TAIL = '444444'\n\n WALL_COUNT = 50\n\n global map_colors\n map_colors = {'-2': f'#{APPLE}' ,\n '-1': f'#{WALL}' ,\n '0' : f'#{GRASS}',\n '1' : f'#{SNAKE}',\n '2' : f'#{TAIL}' }\n Snake(WIDTH, HEIGHT, WALL_COUNT)\n isAlive = False\n","repo_name":"viktor-krasikov/m763","sub_path":"lesson3/panteleev_snake.py","file_name":"panteleev_snake.py","file_ext":"py","file_size_in_byte":5485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18769278247","text":"from django.db import models\nfrom datetime import datetime\nfrom realtors.models import Realtor\n\n# Create your models here.\n\nclass Listing(models.Model):\n realtors = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING)\n title = models.CharField(max_length=200)\n address = models.CharField(max_length=200)\n city = models.CharField(max_length=100)\n state = models.CharField(max_length=100)\n zipcode = models.CharField(max_length=20)\n # blank = True means that this field is optional. So if we are in the admin area and we are creating a listings and we dont put a desc then we wont get an error\n description = models.TextField(blank=True)\n price = models.IntegerField()\n bedrooms = models.IntegerField()\n # we will never have a bathroom with a 100 so max_digit is 2.\n bathrooms = models.DecimalField(max_digits=2, decimal_places=1)\n garage = models.IntegerField(default=0)\n sqft = models.IntegerField()\n # we will have like 2.5 Acres\n lot_size = models.DecimalField(max_digits=5, decimal_places=1)\n photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')\n photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)\n photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)\n photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)\n photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)\n photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)\n photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)\n is_published = models.BooleanField(default=True)\n list_date = models.DateTimeField(default=datetime.now, blank=True)\n\n def __str__(self):\n return self.title\n","repo_name":"utkarsh-srivastava/django-postgre","sub_path":"listings/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"72817591637","text":"\"\"\"\n✅ GOOD Greedy\nDaily Challenge (01/13/2022:01/04/2023)\nLabuladong P381: Greedy (Interval Scheduling)\ntag: medium, Greedy\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n def intervalSchedule():\n \"\"\" \"\n https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/887690/Python-O(n-log-n)-solution-explained\n Runtime: 1236 ms, faster than 93.30% of Python3 online submissions for Minimum Number of Arrows to Burst Balloons.\n\n T: O(N)\n \"\"\"\n points.sort(key=lambda x: x[1])\n n, count = len(points), 1\n if n == 0:\n return 0\n curr = points[0]\n\n for i in range(n):\n if curr[1] < points[i][0]:\n count += 1\n curr = points[i]\n\n return count\n\n return intervalSchedule()\n\n\nsl = Solution()\npoints = [[10, 16], [2, 8], [1, 6], [7, 12]]\npoints = [[1, 2], [3, 4], [5, 6], [7, 8]]\npoints = [[1, 2], [2, 3], [3, 4], [4, 5]]\n\nprint(sl.findMinArrowShots(points))\n","repo_name":"fxrcode/LeetPy","sub_path":"Leet/452_Minimum_Number_of_Arrows_to_Burst_Balloons.py","file_name":"452_Minimum_Number_of_Arrows_to_Burst_Balloons.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"42739808901","text":"from model import ActorCritic\nfrom tensorflow import get_default_session\nimport numpy as np\nfrom tf_utils import compute_gae\n\n\nclass A3C(object):\n def __init__(self, scope, obs_dim, acts_dim, target, network_config):\n self.model = ActorCritic(scope=scope, obs_dim=obs_dim, acts_dim=acts_dim, target=target,\n network_config=network_config)\n\n def train(self, feed_dict): # run by a local\n sess = get_default_session() # local grads applies to global net\n pi_loss, vf_loss, global_step, _ = sess.run(\n [self.model.pi_loss, self.model.vf_loss, self.model.global_step, self.model.train_op], feed_dict)\n return (pi_loss, vf_loss), global_step\n\n def sync_from_target(self): # run by a local\n sess = get_default_session()\n sess.run([\n self.model.sync_op\n ])\n\n def get_v(self, ob):\n sess = get_default_session()\n return sess.run(self.model.v, {self.model.obs: ob})\n\n def step(self, ob): # run by a local\n sess = get_default_session()\n pi, v = sess.run([self.model.pi, self.model.v], feed_dict={self.model.obs: [ob]}) # ob[np.newaxis, :]})\n action = np.random.choice(pi.shape[1], p=pi.ravel()) # select action w.r.t the actions prob\n return action, v[0]\n\n def get_batch(self, batch, ob1, done, gamma=.95, _lambda=1.):\n\n batch = np.array(batch)\n obs = batch[:, 0]\n acts = batch[:, 1]\n rws = batch[:, 2]\n vs = batch[:, 3]\n\n r_hat = 0\n if done == False:\n r_hat = self.get_v(ob=[ob1])[0]\n\n # d_rws, adv = compute_gae(rws =rws, vs= vs, r_hat=r_hat, gamma=gamma, _lambda=_lambda)\n d_rws = []\n for r in rws[::-1]: # reverse buffer r\n r_hat = r + gamma * r_hat\n d_rws.append(r_hat)\n\n d_rws = np.array(d_rws)[::-1] # .copy()\n adv = d_rws - vs\n\n feed_dict = {\n self.model.obs: np.vstack(obs),\n self.model.acts: acts,\n self.model.rws: d_rws,\n self.model.adv: adv # d_rws - np.array(vs)\n }\n return feed_dict\n","repo_name":"d3sm0/a3c","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39816696267","text":"from vector3d.vector import Vector\nimport uuid\nfrom .ui import UI\n\n\nclass NeuronConfiguration:\n name = None\n position = Vector()\n\n def __init__(self) -> None:\n pass\n\n\n# class NeuronNode:\n\n\nclass Neuron:\n def __init__(self, env, config: NeuronConfiguration):\n self.id = uuid.uuid4()\n self.env = env\n self.position = config.position or Vector()\n self.nodes = []\n \n # Start the run process everytime an instance is created.\n self.action = self.env.process(self.run())\n\n def init(self):\n self.action = self.env.process(self.run())\n\n def run(self):\n while True:\n print(\"Start parking and charging at %d\" % self.env.now)\n charge_duration = 5\n UI.send(\"hello\")\n # We yield the process that process() returns\n # to wait for it to finish\n yield self.env.process(self.charge(charge_duration))\n\n print(\"Start driving at %d\" % self.env.now)\n trip_duration = 2\n yield self.env.timeout(trip_duration)\n\n def charge(self, duration):\n yield self.env.timeout(duration)\n","repo_name":"lucascassiano/neuronal-morphogenesis-simulation","sub_path":"python_simulations/core/Neuron.py","file_name":"Neuron.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"41687620853","text":"import json\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.csrf import csrf_protect\nfrom rest_framework.filters import SearchFilter\nfrom rest_framework.generics import ListAPIView\nfrom rest_framework.response import Response\nfrom rest_framework import viewsets, status\nfrom rest_framework.permissions import AllowAny\nfrom django_filters.rest_framework import DjangoFilterBackend\n\nfrom shop.filters import ProductFilter\nfrom shop.models import *\nfrom shop.serializers import SubscriptionSerializer\nfrom shop.forms import EditProfileModelForm\nfrom shop.utils import cart_data, guest_order\n\n\ndef home(request):\n posts = Post.objects.order_by('date')[:4]\n prices = PriceList.objects.all()\n user_id = request.user.id\n context = {\n 'posts': posts,\n 'prices': prices,\n 'user_id': user_id\n }\n return render(request, 'shop/home.html', context)\n\n\ndef train_constructor(request):\n return render(request, 'shop/train_construct.html')\n\n\n@csrf_protect\ndef shop(request):\n user_id = request.user.id\n data = cart_data(request)\n cart_items = data['cart_items']\n\n products = Product.objects.all()\n product_filter = ProductFilter(request.POST, queryset=products)\n products = product_filter.qs\n context = {\n 'products': products,\n 'product_filter': product_filter,\n 'cart_items': cart_items,\n 'user_id': user_id\n }\n return render(request, 'shop/shop.html', context)\n\n\n@csrf_protect\ndef cart(request):\n user_id = request.user.id\n\n data = cart_data(request)\n cart_items = data['cart_items']\n order = data['order']\n items = data['items']\n\n context = {\n 'items': items,\n 'order': order,\n 'cart_items': cart_items,\n 'user_id': user_id\n }\n return render(request, 'shop/cart.html', context)\n\n\ndef update_item(request):\n data = json.loads(request.body)\n product_id = data['productId']\n action = data['action']\n\n customer = request.user.customer\n product = Product.objects.get(id=product_id)\n order, created = Order.objects.get_or_create(customer=customer, complete=False)\n order_item, created = OrderItem.objects.get_or_create(order=order, product=product)\n\n if action == 'add':\n order_item.quantity = (order_item.quantity + 1)\n elif action == 'remove':\n order_item.quantity = (order_item.quantity - 1)\n\n order_item.save()\n\n if order_item.quantity <= 0:\n order_item.delete()\n\n return JsonResponse('Item was added', safe=False)\n\n\ndef checkout(request):\n user_id = request.user.id\n user = request.user\n print(user)\n data = cart_data(request)\n cart_items = data['cart_items']\n order = data['order']\n items = data['items']\n\n context = {\n 'items': items,\n 'order': order,\n 'cart_items': cart_items,\n 'user_id': user_id,\n 'user': user,\n }\n return render(request, 'shop/checkout.html', context)\n\n\ndef process_order(request):\n transaction_id = datetime.datetime.now().timestamp()\n data = json.loads(request.body)\n\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(customer=customer, complete=False)\n else:\n customer, order = guest_order(request, data)\n\n total_str = data['form']['total']\n total_str = total_str.replace(',', '.')\n total = float(total_str)\n order.transaction_id = transaction_id\n if total == order.get_cart_total:\n order.complete = True\n order.save()\n\n if order.shipping:\n ShippingAddress.objects.create(\n customer=customer,\n order=order,\n address=data['shipping']['address'],\n city=data['shipping']['city'],\n state=data['shipping']['state'],\n zip_code=data['shipping']['zipcode'],\n )\n\n return JsonResponse('Payment complete!', safe=False)\n\n\n@csrf_protect\n@login_required(login_url='users:login')\ndef profile(request, id):\n user_id = request.user.id\n if request.method == 'POST':\n form = EditProfileModelForm(request.POST, request.FILES, instance=request.user.profile)\n if form.is_valid():\n form.save()\n return redirect(f'/user/profile/{user_id}/')\n else:\n form = EditProfileModelForm(instance=request.user.profile)\n\n username = request.user.username\n name = request.user.profile.name\n surname = request.user.profile.surname\n age = 0\n if request.user.profile.birthday:\n age = int(datetime.datetime.today().year) - int(request.user.profile.birthday.year)\n\n visited_dates = []\n subscription = []\n if request.user.is_authenticated:\n customer = request.user.customer\n try:\n subscription = Subscription.objects.get(customer=customer)\n visited_dates = subscription.visit_dates\n except Subscription.DoesNotExist:\n visited_dates = ['У вас нет действующего абонемента']\n\n context = {\n 'username': username,\n 'subscription': subscription,\n 'name': name,\n 'surname': surname,\n 'age': age,\n 'dates': visited_dates,\n 'update': form,\n 'user_id': user_id\n }\n return render(request, 'shop/profile.html', context)\n\n\n@csrf_protect\ndef subscription_check(request):\n return render(request, 'shop/qrcode_post_request.html')\n\n\nclass SubscriptionViewSet(viewsets.ModelViewSet):\n queryset = Subscription.objects.all()\n serializer_class = SubscriptionSerializer\n permission_classes = (AllowAny,)\n\n def list(self, request, *args, **kwargs):\n sub = self.queryset.all()\n serializer = self.serializer_class(sub, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def create(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save(request=self.request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n def update(self, request, *args, **kwargs):\n partial = True\n instance = self.get_object()\n serializer = self.get_serializer(instance, data=request.data, partial=partial)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n return Response(serializer.data)\n\n\nclass SubscriptionSearchListAPIView(ListAPIView):\n permission_classes = (AllowAny,)\n queryset = Subscription.objects.all()\n serializer_class = SubscriptionSerializer\n filter_backends = [DjangoFilterBackend, SearchFilter]\n filterset_fields = [\n 'customer', 'id'\n ]\n search_fields = [\n 'customer', 'id'\n ]\n","repo_name":"AlekseiChirkov/sparta","sub_path":"shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9242145431","text":"import sys\nimport cv2\nimport numpy as np\n\n\ndef reorderPts(pts): # 꼭지점 순서 정렬\n idx = np.lexsort((pts[:, 1], pts[:, 0])) # 칼럼0 -> 칼럼1 순으로 정렬한 인덱스를 반환\n pts = pts[idx] # x좌표로 정렬\n\n if pts[0, 1] > pts[1, 1]:\n pts[[0, 1]] = pts[[1, 0]] # 스와핑\n\n if pts[2, 1] < pts[3, 1]:\n pts[[2, 3]] = pts[[3, 2]] # 스와핑\n\n return pts\n\n\n# 영상 불러오기\nfilename = \"C:/gaetamna/AlgorithmServer/tilted_test.png\"\n# filename = \"./registcard_test.png\"\nif len(sys.argv) > 1: #py파일을 실행 시키면서 인자값을 넣으면 그 인자값을 filename으로 지정\n filename = sys.argv[1] #ex) opencv2.py ./test.jpg\n\n\nwin_name = 'scan'\nsrc = cv2.imread(filename)\n\n# 출력 영상 설정\ndw, dh = 720, 400\nsrcQuad = np.array([[0, 0], [0, 0], [0, 0], [0, 0]], np.float32)\ndstQuad = np.array([[0, 0], [0, dh], [dw, dh], [dw, 0]], np.float32)\ndst = np.zeros((dh, dw), np.uint8)\n\n# 입력 영상 전처리\nsrc_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)\n_, src_bin = cv2.threshold(src_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) #영상의 이진화\n\n# 외곽선 검출 및 명함 검출\ncontours, _ = cv2.findContours(src_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\ncpy = src.copy()\nfor pts in contours:\n # 너무 작은 객체는 무시\n if cv2.contourArea(pts) < 1000:\n continue\n\n # 외곽선 근사화\n approx = cv2.approxPolyDP(pts, cv2.arcLength(pts, True) * 0.02, True)\n\n # 컨벡스가 아니고, 사각형이 아니면 무시\n if not cv2.isContourConvex(approx) or len(approx) != 4:\n continue\n\n cv2.polylines(cpy, [approx], True, (0, 255, 0), 2, cv2.LINE_AA)\n srcQuad = reorderPts(approx.reshape(4, 2).astype(np.float32))\n\npers = cv2.getPerspectiveTransform(srcQuad, dstQuad)\ndst = cv2.warpPerspective(src, pers, (dw, dh))\ncv2.imshow(win_name, dst)\ncv2.waitKey(0)\n\n\ndst_gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)\ncv2.imshow(win_name, dst_gray)\ncv2.waitKey(0)","repo_name":"SKshieldus-8/gaetamna","sub_path":"AlgorithmServer/opencv.py","file_name":"opencv.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"37396995626","text":"from fastapi import FastAPI,Request\nfrom fastapi import APIRouter\n#import database for mysql\nimport aiomysql\n#libreria que se importa de configuracion.py (contiene las configuraciones del server)\nfrom configuracion import configuracion\n#pydantic para validar datos\nfrom pydantic import BaseModel\n# parametros de peticiones http en body\nfrom fastapi.param_functions import Body\n#importacion de clases de usuario\nfrom clases.itemMatriculaClass import getItemMatriculasByMatriculaId,addOneItemMatricula\n\nitemMatricula_router = APIRouter()\n\nasync def getConexion():\n conn = await aiomysql.connect(host=configuracion['development'].MYSQL_HOST, user=configuracion['development'].MYSQL_USER, password=configuracion['development'].MYSQL_PASSWORD, db=configuracion['development'].MYSQL_DB, charset='utf8', cursorclass=aiomysql.DictCursor)\n return conn\n\n#get all item matriculas : id_itemMatricula, matricula_itemMatricula, curso_itemMatricula\n@itemMatricula_router.get(\"/getItemMatriculas\")\nasync def getItemMatriculas():\n conn = await getConexion()\n try:\n itemMatriculas=[]\n async with conn.cursor() as cur:\n await cur.execute(\"SELECT id_itemMatricula,matricula_itemMatricula,curso_itemMatricula FROM ItemMatricula\")\n resultado = await cur.fetchall()\n for result in resultado:\n itemMatricula = {'id_itemMatricula': result['id_itemMatricula'],'matricula_itemMatricula': result['matricula_itemMatricula'],'curso_itemMatricula': result['curso_itemMatricula']}\n itemMatriculas.append(itemMatricula)\n return {'data': itemMatriculas, 'accion': True}\n \n except Exception as e:\n return {'data': '', 'accion': False}\n finally:\n conn.close()\n\n#post obtener itemMatriculas by matricula_itemMatricula\n@itemMatricula_router.post(\"/getItemMatriculasByMatriculaId\")\nasync def getItemMatriculasByMatriculaId(request: Request, itemMatricula: getItemMatriculasByMatriculaId = Body(...)):\n conn = await getConexion()\n try:\n itemMatriculas=[]\n async with conn.cursor() as cur:\n await cur.execute(\"SELECT id_itemMatricula,matricula_itemMatricula,curso_itemMatricula FROM ItemMatricula WHERE matricula_itemMatricula=%s\", (itemMatricula.matricula_itemMatricula))\n resultado = await cur.fetchall()\n for result in resultado:\n itemMatricula = {'id_itemMatricula': result['id_itemMatricula'],'matricula_itemMatricula': result['matricula_itemMatricula'],'curso_itemMatricula': result['curso_itemMatricula']}\n itemMatriculas.append(itemMatricula)\n return {'data': itemMatriculas, 'accion': True}\n \n except Exception as e:\n return {'data': '', 'accion': False}\n finally:\n conn.close()\n\n\n@itemMatricula_router.post(\"/addItemMatriculas\")\nasync def addItemMatriculas(request: Request, itemMatricula: addOneItemMatricula = Body(...)):\n conn = await getConexion()\n try:\n #obtener username por medio del body del api\n matricula_itemMatricula = itemMatricula.matricula_itemMatricula\n curso_itemMatricula = itemMatricula.curso_itemMatricula\n \n global insertado\n insertado=False\n #insertar itemMatricula\n async with conn.cursor() as cur:\n await cur.execute(\"INSERT INTO ItemMatricula (matricula_itemMatricula, curso_itemMatricula) VALUES ('{0}', '{1}');\".format(matricula_itemMatricula,curso_itemMatricula))\n await conn.commit()\n #obtener true si se inserto correctamente\n if cur.rowcount > 0:\n insertado=True\n \n return {'data': {'insertado':insertado}, 'accion': True}\n except Exception as e:\n return {'data': '', 'accion': False}\n finally:\n conn.close()\n","repo_name":"boomcrash/Aula-Estudiantil-Back-End","sub_path":"src/controladores/itemMatriculaController.py","file_name":"itemMatriculaController.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42055806458","text":"# 1\nlist = [1, 2, 3, 4, 5]\n#And a for loop:\n\nfor i in range(len(list)-1):\n if list[i] > 3:\n list.clear()\n list.append(1)\nprint(list)\n\n\nlist_1 = [['a', 'b'], ['a', 'c'], ['a', 'c'], ['a', 'c'], ['b', 'e'], ['d', 'q'], ['d', 'q']]\nnew_dict={}\nnew_list=[]\nentry = ()\nfor l in list_1:\n if tuple(l) in new_dict:\n new_dict[tuple(l)] += 1\n else:\n new_dict[tuple(l)] = 1\nfor key in new_dict:\n entry = list(key)\n entry.append(new_dict[key])\n new_list.append(entry)\nprint (new_list)","repo_name":"SnakeMM1/Prace_domowe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21793405747","text":"import pygame\nimport cocolady\nimport gringo\nimport fatjoe\nimport sprites\nimport random\n\n# initialize pygame\npygame.mixer.pre_init(44100, -16, 1, 512)\npygame.init()\n\n# create a game display\npygame.display.set_icon(sprites.icon)\ndisplay_width = 800\ndisplay_height = 600\ngame_display = pygame.display.set_mode((display_width, display_height))\n\n# 8 bit madness font can be downloaded from here: http://www.dafont.com/8-bit-madness.font\nfont = \"8-Bit-Madness.ttf\"\n\n\n# text rendering function\ndef message_to_screen(message, textfont, size, color):\n my_font = pygame.font.Font(textfont, size)\n my_message = my_font.render(message, 0, color)\n\n return my_message\n\n# colors\nwhite = (255, 255, 255)\nblack = (0, 0, 0)\ngray = (50, 50, 50)\nred = (255, 0, 0)\ngreen = (0, 255, 0)\nblue = (0, 0, 255)\nyellow = (255, 255, 0)\n\n# sprite pixel format converting\nfor convert_sprites in sprites.all_sprites:\n convert_sprites.convert_alpha()\n\n# framerate\nclock = pygame.time.Clock()\nFPS = 30\n\n# player variables\nplayer = cocolady.Cocolady(100, display_height/2-40)\nmoving = True\ngodmode = False\n\n# score variables\nscore = 0\nhighscore_file = open('highscore.dat', \"r\")\nhighscore_int = int(highscore_file.read())\n\n# cloud variables\ncloud_x = 800\ncloud_y = random.randint(0, 400)\n\n# gringo variables\ngringo = gringo.Gringo(-100, display_height/2-40)\ngringo_alive = False\n\n# FatJoe variables\nfatjoe = fatjoe.FatJoe(-110, 430)\nfatjoe_alive = False\n\n# karen variables\nkaren_x = 800\nkaren_y = random.randint(0, 400)\nkaren_alive = False\nkaren_hit_player = False\nwarning_once = True\nwarning = False\nwarning_counter = 0\nwarning_message = message_to_screen(\"!\", font, 200, red)\n\n# crab variables\ncrab_x = 800\ncrab= random.randint(0, 400)\n\n# bullet variables\nbullets = []\n\n# bomb variables\nbombs = []\n\n# sounds\npop = pygame.mixer.Sound('sounds/pop.wav')\nshoot = pygame.mixer.Sound('sounds/shoot.wav')\nbomb = pygame.mixer.Sound('sounds/bomb.wav')\nexplosion = pygame.mixer.Sound('sounds/explosion.wav')\nexplosion2 = pygame.mixer.Sound('sounds/explosion2.wav')\nselect = pygame.mixer.Sound('sounds/select.wav')\nselect2 = pygame.mixer.Sound('sounds/select2.wav')\nalert = pygame.mixer.Sound('sounds/alert.wav')\nwhoosh = pygame.mixer.Sound('sounds/whoosh.wav')\n\n\n# main menu\ndef main_menu():\n\n global cloud_x\n global cloud_y\n\n menu = True\n\n selected = \"play\"\n\n while menu:\n\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_w or event.key == pygame.K_UP:\n pygame.mixer.Sound.play(select)\n selected = \"play\"\n elif event.key == pygame.K_s or event.key == pygame.K_DOWN:\n pygame.mixer.Sound.play(select)\n selected = \"quit\"\n if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:\n pygame.mixer.Sound.play(select2)\n if selected == \"play\":\n menu = False\n if selected == \"quit\":\n pygame.quit()\n quit()\n\n # drawing background\n game_display.blit(sprites.background, (0, 0))\n\n game_display.blit(sprites.cloud, (cloud_x, cloud_y))\n if cloud_x <= 800 - 1100:\n cloud_x = 800\n cloud_y = random.randint(0, 400)\n else:\n if not player.wreck_start:\n cloud_x -= 5\n if godmode:\n title = message_to_screen(\"COCOLADY (GODMODE)\", font, 80, yellow)\n else:\n title = message_to_screen(\"COCOLADY\", font, 100, black)\n controls_1 = message_to_screen(\"use WASD to move, SPACE to shoot,\", font, 30, black)\n controls_2 = message_to_screen(\"SHIFT to drop bombs, and P to toggle pause\", font, 30, black)\n if selected == \"play\":\n play = message_to_screen(\"PLAY\", font, 75, white)\n else:\n play = message_to_screen(\"PLAY\", font, 75, black)\n if selected == \"quit\":\n game_quit = message_to_screen(\"QUIT\", font, 75, white)\n else:\n game_quit = message_to_screen(\"QUIT\", font, 75, black)\n\n title_rect = title.get_rect()\n controls_1_rect = controls_1.get_rect()\n controls_2_rect = controls_2.get_rect()\n play_rect = play.get_rect()\n quit_rect = game_quit.get_rect()\n\n # drawing text\n game_display.blit(title, (display_width/2 - (title_rect[2]/2), 40))\n game_display.blit(controls_1, (display_width/2 - (controls_1_rect[2]/2), 120))\n game_display.blit(controls_2, (display_width/2 - (controls_2_rect[2]/2), 140))\n game_display.blit(play, (display_width/2 - (play_rect[2]/2), 200))\n game_display.blit(game_quit, (display_width/2 - (quit_rect[2]/2), 260))\n # drawing ocean\n pygame.draw.rect(game_display, blue, (0, 500, 800, 100))\n\n pygame.display.update()\n pygame.display.set_caption(\"COCOLADY running at \" + str(int(clock.get_fps())) + \" frames per second.\")\n clock.tick(FPS)\n\n\ndef pause():\n\n global highscore_file\n global highscore_int\n\n paused = True\n\n player.moving_up = False\n player.moving_left = False\n player.moving_down = False\n player.moving_right = False\n\n paused_text = message_to_screen(\"PAUSED\", font, 100, black)\n paused_text_rect = paused_text.get_rect()\n\n game_display.blit(paused_text, (display_width/2 - (paused_text_rect[2]/2), 40))\n\n pygame.display.update()\n clock.tick(15)\n\n while paused:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n if score > highscore_int:\n highscore_file = open('highscore.dat', \"w\")\n highscore_file.write(str(score))\n highscore_file.close()\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_p:\n pygame.mixer.Sound.play(select)\n paused = False\n\n\n# create a game loop\ndef game_loop():\n\n global karen_x\n global karen_y\n global karen_alive\n global karen_hit_player\n global warning\n global warning_counter\n global warning_once\n\n global bullets\n global moving\n\n global highscore_file\n global highscore_int\n global score\n\n global cloud_x\n global cloud_y\n\n global crab_x\n global crab_y\n\n global gringo_alive\n\n global fatjoe_alive\n\n game_exit = False\n game_over = False\n\n game_over_selected = \"play again\"\n\n while not game_exit:\n\n while game_over:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n if score > highscore_int:\n highscore_file = open('highscore.dat', \"w\")\n highscore_file.write(str(score))\n highscore_file.close()\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w or event.key == pygame.K_UP:\n pygame.mixer.Sound.play(select)\n game_over_selected = \"play again\"\n elif event.key == pygame.K_s or event.key == pygame.K_DOWN:\n pygame.mixer.Sound.play(select)\n game_over_selected = \"quit\"\n if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:\n pygame.mixer.Sound.play(select2)\n if game_over_selected == \"play again\":\n if score > highscore_int:\n highscore_file = open('highscore.dat', \"w\")\n highscore_file.write(str(score))\n highscore_file.close()\n game_over = False\n\n score = 0\n\n crab_x = 800\n\n gringo.x = -100\n gringo_alive = False\n gringo.bullets = []\n\n fatjoe.x = -110\n fatjoe_alive = False\n fatjoe.bullets = []\n\n karen_x = 800\n karen_alive = False\n warning = False\n warning_counter = 0\n warning_counter = 0\n\n player.wreck_start = False\n player.y = display_height/2-40\n player.x = 100\n player.wrecked = False\n player.health = 3\n bullets = []\n\n game_loop()\n if game_over_selected == \"quit\":\n pygame.quit()\n quit()\n\n game_over_text = message_to_screen(\"GAME OVER\", font, 100, black)\n your_score = message_to_screen(\"YOUR SCORE WAS: \" + str(score), font, 50, black)\n if game_over_selected == \"play again\":\n play_again = message_to_screen(\"PLAY AGAIN\", font, 75, white)\n else:\n play_again = message_to_screen(\"PLAY AGAIN\", font, 75, black)\n if game_over_selected == \"quit\":\n game_quit = message_to_screen(\"QUIT\", font, 75, white)\n else:\n game_quit = message_to_screen(\"QUIT\", font, 75, black)\n\n game_over_rect = game_over_text.get_rect()\n your_score_rect = your_score.get_rect()\n play_again_rect = play_again.get_rect()\n game_quit_rect = game_quit.get_rect()\n\n game_display.blit(game_over_text, (display_width/2 - game_over_rect[2]/2, 40))\n game_display.blit(your_score, (display_width/2 - (your_score_rect[2]/2+5), 100))\n game_display.blit(play_again, (display_width/2 - play_again_rect[2]/2, 200))\n game_display.blit(game_quit, (display_width/2 - game_quit_rect[2]/2, 260))\n\n pygame.display.update()\n pygame.display.set_caption(\"COCOLADY running at \" + str(int(clock.get_fps())) + \" frames per second.\")\n clock.tick(10)\n\n # event handler\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n if score > highscore_int:\n highscore_file = open('highscore.dat', \"w\")\n highscore_file.write(str(score))\n highscore_file.close()\n pygame.quit()\n quit()\n\n if moving:\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w:\n player.moving_up = True\n if event.key == pygame.K_a:\n player.moving_left = True\n if event.key == pygame.K_s:\n player.moving_down = True\n if event.key == pygame.K_d:\n player.moving_right = True\n if event.key == pygame.K_SPACE:\n if not player.wreck_start:\n pygame.mixer.Sound.play(shoot)\n bullets.append([player.x, player.y])\n if event.key == pygame.K_LSHIFT:\n if not player.wreck_start:\n pygame.mixer.Sound.play(bomb)\n bombs.append([player.x, player.y])\n if event.key == pygame.K_p:\n pygame.mixer.Sound.play(select)\n pause()\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_w:\n player.moving_up = False\n if event.key == pygame.K_a:\n player.moving_left = False\n if event.key == pygame.K_s:\n player.moving_down = False\n if event.key == pygame.K_d:\n player.moving_right = False\n\n if player.health < 1:\n pygame.mixer.Sound.play(explosion)\n player.wreck()\n\n if player.wrecked:\n game_over = True\n\n # draw background and randomly positioned clouds\n game_display.blit(sprites.background, (0, 0))\n\n game_display.blit(sprites.cloud, (cloud_x, cloud_y))\n if cloud_x <= 800 - 1100:\n cloud_x = 800\n cloud_y = random.randint(0, 400)\n else:\n if not player.wreck_start:\n cloud_x -= 5\n\n # drawing player\n game_display.blit(player.current, (player.x, player.y))\n\n # drawing Gringo\n game_display.blit(gringo.current, (gringo.x, gringo.y))\n\n # drawing karen\n game_display.blit(sprites.karen, (karen_x, karen_y))\n\n # drawing fatjoe\n game_display.blit(sprites.fatjoe, (fatjoe.x, fatjoe.y))\n\n # enabling movement and animations\n player.player_init()\n gringo.init()\n fatjoe.init()\n\n # rendering bullets\n if not player.wreck_start and not player.wrecked:\n for draw_bullet in bullets:\n pygame.draw.rect(game_display, black, (draw_bullet[0]+90, draw_bullet[1]+40, 10, 10))\n for move_bullet in range(len(bullets)):\n bullets[move_bullet][0] += 40\n for del_bullet in bullets:\n if del_bullet[0] >= 800:\n bullets.remove(del_bullet)\n\n # rendering bombs\n if not player.wreck_start and not player.wrecked:\n for draw_bomb in bombs:\n pygame.draw.rect(game_display, black, (draw_bomb[0]+55, draw_bomb[1]+70, 20, 20))\n for move_bomb in range(len(bombs)):\n bombs[move_bomb][1] += 20\n for del_bomb in bombs:\n if del_bomb[1] > 600:\n bombs.remove(del_bomb)\n\n # rendering gringo bullets\n if not player.wreck_start and not player.wrecked and not game_over:\n for draw_bullet in gringo.bullets:\n pygame.draw.rect(game_display, gray, (draw_bullet[0], draw_bullet[1]+40, 40, 10))\n pygame.draw.rect(game_display, red, (draw_bullet[0]+30, draw_bullet[1]+40, 10, 10))\n for move_bullet in range(len(gringo.bullets)):\n gringo.bullets[move_bullet][0] -= 15\n for del_bullet in gringo.bullets:\n if del_bullet[0] <= -40:\n gringo.bullets.remove(del_bullet)\n\n # rendering fatjoe bullets\n if not player.wreck_start and not player.wrecked and not game_over:\n for draw_bullet in fatjoe.bullets:\n pygame.draw.rect(game_display, gray, (draw_bullet[0]+40, draw_bullet[1]+30, 20, 20))\n for move_bullet in range(len(fatjoe.bullets)):\n fatjoe.bullets[move_bullet][0] -= 10\n fatjoe.bullets[move_bullet][1] -= 10\n for del_bullet in fatjoe.bullets:\n if del_bullet[1] < -40:\n fatjoe.bullets.remove(del_bullet)\n\n # draw randomly positioned crabs, pop if they hit any bullet or bombs\n for pop_crab in bullets:\n if crab_x < pop_crab[0]+90 < crab_x+70 and crab_y < pop_crab[1]+40 < crab_y+100:\n pygame.mixer.Sound.play(pop)\n bullets.remove(pop_crab)\n crab_x = 800-870\n score += 50\n elif crab_x < pop_crab[0]+100 < crab_x+70 and crab_y < pop_crab[1]+50 < crab_y+100:\n pygame.mixer.Sound.play(pop)\n bullets.remove(pop_crab)\n crab_x = 800-870\n score += 50\n\n for pop_crab in bombs:\n if crab_x < pop_crab[0]+55 < crab_x+70 and crab_y < pop_crab[1]+70 < crab_y+100:\n pygame.mixer.Sound.play(pop)\n bombs.remove(pop_crab)\n crab_x = 800-870\n score += 50\n elif crab_x < pop_crab[0]+75 < crab_x+70 and crab_y < pop_crab[1]+90 < crab_y+100:\n pygame.mixer.Sound.play(pop)\n bombs.remove(pop_crab)\n crab_x = 800-870\n score += 50\n\n # spawn karen randomly\n karen_spawn_num = random.randint(0, 100)\n if karen_spawn_num == 50 and not karen_alive and score > 450:\n warning = True\n\n # show warning before karen spawning\n if warning:\n if warning_once:\n pygame.mixer.Sound.play(alert)\n warning_once = False\n game_display.blit(warning_message, (750, karen_y-15))\n if warning_counter > 45:\n pygame.mixer.Sound.play(whoosh)\n karen_alive = True\n warning_counter = 0\n warning = False\n warning_once = True\n else:\n warning_counter += 1\n\n # karen movement\n if karen_alive:\n karen_x -= 30\n if karen_x < 0-100:\n karen_hit_player = False\n karen_alive = False\n karen_x = 800\n karen_y = random.randint(0, 400)\n\n # spawn gringo randomly\n gringo_spawn_num = random.randint(0, 100)\n if not gringo_alive and score > 250 and gringo_spawn_num == 50:\n gringo_alive = True\n gringo.x = 800\n\n # spawn fatjoe randomly\n fatjoe_spawn_num = random.randint(0, 200)\n if score > 700 and fatjoe_spawn_num == 100 and not fatjoe_alive:\n fatjoe.x = 800\n fatjoe_alive = True\n\n if fatjoe.x <= -110:\n fatjoe_alive = False\n\n # gringo-player bullet collision detection\n for hit_gringo in bullets:\n if gringo.x < hit_gringo[0]+90 < gringo.x+00 \\\n or gringo.x < hit_gringo[0]+100 < gringo.y+00:\n if gringo.y < hit_gringo[1]+40 < gringo.y+80 \\\n or gringo.y < hit_gringo[1]+50 < gringo.y+80:\n if not gringo.x > 600:\n pygame.mixer.Sound.play(explosion2)\n score += 150\n bullets.remove(hit_gringo)\n gringo.x = -100\n gringo_alive = False\n\n # karen-player bullet/bomb collision detection\n for hit_karen in bullets:\n if karen_x < hit_karen[0]+90 < karen_x+100 \\\n or karen_x < hit_karen[0]+100 < karen_x+100:\n if karen_y < hit_karen[1]+40 < karen_y+80 \\\n or karen_y < hit_karen[1]+50 < karen_y+80:\n if not karen_x > 700:\n pygame.mixer.Sound.play(explosion2)\n bullets.remove(hit_karen)\n score += 200\n karen_hit_player = False\n karen_alive = False\n karen_x = 800\n karen_y = random.randint(0, 400)\n\n for hit_karen in bombs:\n if karen_x < hit_karen[0]+55 < karen_x+100 \\\n or karen_x < hit_karen[0]+65 < karen_x+100:\n if karen_y < hit_karen[1]+70 < karen_y+80 \\\n or karen_y < hit_karen[1]+80 < karen_y+80:\n if not karen_x > 700:\n pygame.mixer.Sound.play(explosion2)\n bombs.remove(hit_karen)\n score += 200\n karen_hit_player = False\n karen_alive = False\n karen_x = 800\n karen_y = random.randint(0, 400)\n\n # fatjoe-player bullet/bomb collision detection\n for hit_fatjoe in bullets:\n if fatjoe.x < hit_fatjoe[0]+90 < fatjoe.x+110 or fatjoe.x < hit_karen[0]+100 < fatjoe.x+110:\n if fatjoe.y < hit_fatjoe[1]+40 < fatjoe.y+70 or fatjoe.y < hit_fatjoe[1]+50 < fatjoe.y+70:\n if not fatjoe.x > 780:\n pygame.mixer.Sound.play(explosion2)\n bullets.remove(hit_fatjoe)\n score += 200\n fatjoe_alive = False\n fatjoe.x = -110\n\n for hit_fatjoe in bombs:\n if fatjoe.x < hit_fatjoe[0]+55 < fatjoe.x+110 or fatjoe.x < hit_karen[0]+75 < fatjoe.x+110:\n if fatjoe.y < hit_fatjoe[1]+70 < fatjoe.y+70 or fatjoe.y < hit_fatjoe[1]+90 < fatjoe.y+70:\n if not fatjoe.x > 780:\n pygame.mixer.Sound.play(explosion2)\n bombs.remove(hit_fatjoe)\n score += 200\n fatjoe_alive = False\n fatjoe.x = -110\n\n # player-ballon collision detection\n if crab_x < player.x < crab_x+70 or crab_x < player.x+100 < crab_x+70:\n if crab_y < player.y < crab_y+80 or crab_y < player.y+80 < crab_y+80:\n pygame.mixer.Sound.play(explosion)\n player.damaged = True\n player.health -= 1\n crab_x = 800-870\n\n # player-gringo rocket collision detection\n for hit_player in gringo.bullets:\n if player.x < hit_player[0] < player.x+100 or player.x < hit_player[0]+40 < player.x+100:\n if player.y < hit_player[1]+40 < player.y+80 or player.y < hit_player[1]+50 < player.y+80:\n pygame.mixer.Sound.play(explosion)\n player.damaged = True\n player.health -= 1\n gringo.bullets.remove(hit_player)\n\n # player-fatjoe bullet collision detection\n for hit_player in fatjoe.bullets:\n if player.x < hit_player[0] < player.x+100 or player.x < hit_player[0]+20 < player.x+100:\n if player.y < hit_player[1] < player.y+80 or player.y < hit_player[1]+20 < player.y+80:\n pygame.mixer.Sound.play(explosion)\n if not fatjoe.fatjoe_hit_player:\n player.damaged = True\n player.health -= 1\n fatjoe.bullets.remove(hit_player)\n\n # player-fatjoe collision detection\n if fatjoe.x < player.x < fatjoe.x+110 or fatjoe.x < player.x+100 < fatjoe.x+110:\n if fatjoe.y < player.y < fatjoe.y+70 or fatjoe.y < player.y+80 < fatjoe.y+70:\n if not fatjoe.fatjoe_hit_player:\n pygame.mixer.Sound.play(explosion)\n player.damaged = True\n player.health -= 1\n fatjoe.fatjoe_hit_player = True\n\n # player-karen collision detection\n if karen_x < player.x < karen_x+100 or karen_x < player.x+100 < karen_x+100:\n if karen_y < player.y < karen_y+88 or karen_y < player.y+80 < karen_y+88:\n if not karen_hit_player:\n pygame.mixer.Sound.play(explosion)\n player.damaged = True\n player.health -= 1\n karen_hit_player = True\n\n game_display.blit(sprites.crab, (crab_x,crab_y))\n if crab_x <= 800 - 870:\n crab_x = 800\n crab_y = random.randint(0, 400)\n else:\n if not player.wreck_start:\n crab_x -= 7\n\n # draw score\n game_display.blit(message_to_screen(\"SCORE: {0}\".format(score), font, 50, black), (10, 10))\n\n # draw high score\n if score < highscore_int:\n hi_score_message = message_to_screen(\"HI-SCORE: {0}\".format(highscore_int), font, 50, black)\n else:\n highscore_file = open('highscore.dat', \"w\")\n highscore_file.write(str(score))\n highscore_file.close()\n highscore_file = open('highscore.dat', \"r\")\n highscore_int = int(highscore_file.read())\n highscore_file.close()\n hi_score_message = message_to_screen(\"HI-SCORE: {0}\".format(highscore_int), font, 50, yellow)\n\n hi_score_message_rect = hi_score_message.get_rect()\n\n game_display.blit(hi_score_message, (800-hi_score_message_rect[2]-10, 10))\n\n # draw health\n if player.health >= 1:\n game_display.blit(sprites.icon, (10, 50))\n if player.health >= 2:\n game_display.blit(sprites.icon, (10+32+10, 50))\n if player.health >= 3:\n game_display.blit(sprites.icon, (10+32+10+32+10, 50))\n\n # god-mode (for quicker testing)\n if godmode:\n score = 1000\n player.health = 3\n\n # drawing ocean\n pygame.draw.rect(game_display, blue, (0, 500, 800, 100))\n\n pygame.display.update()\n\n pygame.display.set_caption(\"COCOLADY running at \" + str(int(clock.get_fps())) + \" frames per second.\")\n clock.tick(FPS)\n\n\nmain_menu()\ngame_loop()\npygame.quit()\nquit()\n","repo_name":"trinway2swag/pls-work","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":25060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28696838824","text":"import math\nfrom contextlib import suppress\nfrom typing import Callable, List, Optional, Union\n\nimport torch\nfrom torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler\n\nfrom .logging import get_logger\nfrom .state import AcceleratorState, DistributedType, GradientState, is_tpu_available\nfrom .utils import (\n RNGType,\n broadcast,\n broadcast_object_list,\n concatenate,\n find_batch_size,\n get_data_structure,\n initialize_tensors,\n is_torch_version,\n send_to_device,\n slice_tensors,\n synchronize_rng_states,\n)\n\n\nlogger = get_logger(__name__)\n\n# kwargs of the DataLoader in min version 1.4.0.\n_PYTORCH_DATALOADER_KWARGS = {\n \"batch_size\": 1,\n \"shuffle\": False,\n \"sampler\": None,\n \"batch_sampler\": None,\n \"num_workers\": 0,\n \"collate_fn\": None,\n \"pin_memory\": False,\n \"drop_last\": False,\n \"timeout\": 0,\n \"worker_init_fn\": None,\n \"multiprocessing_context\": None,\n \"generator\": None,\n \"prefetch_factor\": 2,\n \"persistent_workers\": False,\n}\n\n# kwargs added after by version\n_PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {}\n\nfor v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items():\n if is_torch_version(\">=\", v):\n _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs)\n\n\nclass SeedableRandomSampler(RandomSampler):\n \"\"\"\n Same as a random sampler, except that in `__iter__` a seed can be used.\n\n Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed\n and be fully reproducable on multiple iterations.\n\n If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on\n (stored in `self.epoch`).\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.epoch = 0\n\n def __iter__(self):\n if self.generator is None:\n self.generator = torch.Generator()\n # Allow `self.epoch` to modify the seed of the generator\n seed = self.epoch + self.generator.initial_seed()\n self.generator.manual_seed(seed)\n yield from super().__iter__()\n self.set_epoch(self.epoch + 1)\n\n def set_epoch(self, epoch: int):\n \"Sets the current iteration of the sampler.\"\n self.epoch = epoch\n\n\nclass BatchSamplerShard(BatchSampler):\n \"\"\"\n Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will\n always yield a number of batches that is a round multiple of `num_processes` and that all have the same size.\n Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration\n at the first batch that would be too small / not present on all processes or loop with indices from the beginning.\n\n Args:\n batch_sampler (`torch.utils.data.sampler.BatchSampler`):\n The batch sampler to split in several shards.\n num_processes (`int`, *optional*, defaults to 1):\n The number of processes running concurrently.\n process_index (`int`, *optional*, defaults to 0):\n The index of the current process.\n split_batches (`bool`, *optional*, defaults to `False`):\n Whether the shards should be created by splitting a batch to give a piece of it on each process, or by\n yielding different full batches on each process.\n\n On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in:\n\n - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if\n this argument is set to `False`.\n - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]`\n then `[6, 7]` if this argument is set to `True`.\n even_batches (`bool`, *optional*, defaults to `True`):\n Whether or not to loop back at the beginning of the sampler when the number of samples is not a round\n multiple of (original batch size / number of processes).\n\n \n\n `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`\n equal to `False`\n\n \"\"\"\n\n def __init__(\n self,\n batch_sampler: BatchSampler,\n num_processes: int = 1,\n process_index: int = 0,\n split_batches: bool = False,\n even_batches: bool = True,\n ):\n if split_batches and batch_sampler.batch_size % num_processes != 0:\n raise ValueError(\n f\"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({batch_sampler.batch_size}) \"\n f\"needs to be a round multiple of the number of processes ({num_processes}).\"\n )\n self.batch_sampler = batch_sampler\n self.num_processes = num_processes\n self.process_index = process_index\n self.split_batches = split_batches\n self.even_batches = even_batches\n self.batch_size = getattr(batch_sampler, \"batch_size\", None)\n self.drop_last = getattr(batch_sampler, \"drop_last\", False)\n if self.batch_size is None and self.even_batches:\n raise ValueError(\"You need to use `even_batches=False` when the batch sampler has no batch size.\")\n\n @property\n def total_length(self):\n return len(self.batch_sampler)\n\n def __len__(self):\n if self.split_batches:\n # Split batches does not change the length of the batch sampler\n return len(self.batch_sampler)\n if len(self.batch_sampler) % self.num_processes == 0:\n # If the length is a round multiple of the number of processes, it's easy.\n return len(self.batch_sampler) // self.num_processes\n length = len(self.batch_sampler) // self.num_processes\n if self.drop_last:\n # Same if we drop the remainder.\n return length\n elif self.even_batches:\n # When we even batches we always get +1\n return length + 1\n else:\n # Otherwise it depends on the process index.\n return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length\n\n def __iter__(self):\n return self._iter_with_split() if self.split_batches else self._iter_with_no_split()\n\n def _iter_with_split(self):\n initial_data = []\n batch_length = self.batch_sampler.batch_size // self.num_processes\n for idx, batch in enumerate(self.batch_sampler):\n if idx == 0:\n initial_data = batch\n if len(batch) == self.batch_size:\n # If the batch is full, we yield the part of it this process is responsible of.\n yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]\n\n # If drop_last is True of the last batch was full, iteration is over, otherwise...\n if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size:\n if not self.even_batches:\n if len(batch) > batch_length * self.process_index:\n yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]\n else:\n # For degenerate cases where the dataset has less than num_process * batch_size samples\n while len(initial_data) < self.batch_size:\n initial_data += initial_data\n batch = batch + initial_data\n yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]\n\n def _iter_with_no_split(self):\n initial_data = []\n batch_to_yield = []\n for idx, batch in enumerate(self.batch_sampler):\n # We gather the initial indices in case we need to circle back at the end.\n if not self.drop_last and idx < self.num_processes:\n initial_data += batch\n # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually\n # yielding it.\n if idx % self.num_processes == self.process_index:\n batch_to_yield = batch\n if idx % self.num_processes == self.num_processes - 1 and (\n self.batch_size is None or len(batch) == self.batch_size\n ):\n yield batch_to_yield\n batch_to_yield = []\n\n # If drop_last is True, iteration is over, otherwise...\n if not self.drop_last and len(initial_data) > 0:\n if not self.even_batches:\n if len(batch_to_yield) > 0:\n yield batch_to_yield\n else:\n # ... we yield the complete batch we had saved before if it has the proper length\n if len(batch_to_yield) == self.batch_size:\n yield batch_to_yield\n\n # For degenerate cases where the dataset has less than num_process * batch_size samples\n while len(initial_data) < self.num_processes * self.batch_size:\n initial_data += initial_data\n\n # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next\n if len(batch) == self.batch_size:\n batch = []\n idx += 1\n\n # Make sure we yield a multiple of self.num_processes batches\n cycle_index = 0\n while idx % self.num_processes != 0 or len(batch) > 0:\n end_index = cycle_index + self.batch_size - len(batch)\n batch += initial_data[cycle_index:end_index]\n if idx % self.num_processes == self.process_index:\n yield batch\n cycle_index = end_index\n batch = []\n idx += 1\n\n\nclass IterableDatasetShard(IterableDataset):\n \"\"\"\n Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will\n always yield a number of samples that is a round multiple of the actual batch size (depending of the value of\n `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the\n `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would\n be too small or loop with indices from the beginning.\n\n Args:\n dataset (`torch.utils.data.dataset.IterableDataset`):\n The batch sampler to split in several shards.\n batch_size (`int`, *optional*, defaults to 1):\n The size of the batches per shard (if `split_batches=False`) or the size of the batches (if\n `split_batches=True`).\n drop_last (`bool`, *optional*, defaults to `False`):\n Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the\n beginning.\n num_processes (`int`, *optional*, defaults to 1):\n The number of processes running concurrently.\n process_index (`int`, *optional*, defaults to 0):\n The index of the current process.\n split_batches (`bool`, *optional*, defaults to `False`):\n Whether the shards should be created by splitting a batch to give a piece of it on each process, or by\n yielding different full batches on each process.\n\n On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in:\n\n - the shard on process 0 to yield `[0, 1, 2, 3]` and the shard on process 1 to yield `[4, 5, 6, 7]` if this\n argument is set to `False`.\n - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if\n this argument is set to `True`.\n \"\"\"\n\n def __init__(\n self,\n dataset: IterableDataset,\n batch_size: int = 1,\n drop_last: bool = False,\n num_processes: int = 1,\n process_index: int = 0,\n split_batches: bool = False,\n ):\n if split_batches and batch_size > 1 and batch_size % num_processes != 0:\n raise ValueError(\n f\"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) \"\n f\"needs to be a round multiple of the number of processes ({num_processes}).\"\n )\n self.dataset = dataset\n self.batch_size = batch_size\n self.drop_last = drop_last\n self.num_processes = num_processes\n self.process_index = process_index\n self.split_batches = split_batches\n\n def set_epoch(self, epoch):\n self.epoch = epoch\n if hasattr(self.dataset, \"set_epoch\"):\n self.dataset.set_epoch(epoch)\n\n def __len__(self):\n # We will just raise the downstream error if the underlying dataset is not sized\n if self.drop_last:\n return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size\n else:\n return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size\n\n def __iter__(self):\n if (\n not hasattr(self.dataset, \"set_epoch\")\n and hasattr(self.dataset, \"generator\")\n and isinstance(self.dataset.generator, torch.Generator)\n ):\n self.dataset.generator.manual_seed(self.epoch)\n real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes)\n process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size\n process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size)\n\n first_batch = None\n current_batch = []\n for element in self.dataset:\n current_batch.append(element)\n # Wait to have a full batch before yielding elements.\n if len(current_batch) == real_batch_size:\n for i in process_slice:\n yield current_batch[i]\n if first_batch is None:\n first_batch = current_batch.copy()\n current_batch = []\n\n # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning.\n if not self.drop_last and len(current_batch) > 0:\n if first_batch is None:\n first_batch = current_batch.copy()\n while len(current_batch) < real_batch_size:\n current_batch += first_batch\n for i in process_slice:\n yield current_batch[i]\n\n\nclass DataLoaderStateMixin:\n \"\"\"\n Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the\n end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other\n useful information that might be needed.\n\n **Available attributes:**\n\n - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch\n - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total\n batch size\n\n \"\"\"\n\n def __init_subclass__(cls, **kwargs):\n cls.end_of_dataloader = False\n cls.remainder = -1\n\n def reset(self):\n self.end_of_dataloader = False\n self.remainder = -1\n\n def begin(self):\n \"Prepares the gradient state for the current dataloader\"\n self.reset()\n with suppress(Exception):\n if not self._drop_last:\n length = getattr(self.dataset, \"total_dataset_length\", len(self.dataset))\n self.remainder = length % self.total_batch_size\n self.gradient_state._add_dataloader(self)\n\n def end(self):\n \"Cleans up the gradient state after exiting the dataloader\"\n self.gradient_state._remove_dataloader(self)\n\n\nclass DataLoaderShard(DataLoader, DataLoaderStateMixin):\n \"\"\"\n Subclass of a PyTorch `DataLoader` that will deal with device placement and current distributed setup.\n\n Args:\n dataset (`torch.utils.data.dataset.Dataset`):\n The dataset to use to build this datalaoder.\n device (`torch.device`, *optional*):\n If passed, the device to put all batches on.\n rng_types (list of `str` or [`~utils.RNGType`]):\n The list of random number generators to synchronize at the beginning of each iteration. Should be one or\n several of:\n\n - `\"torch\"`: the base torch random number generator\n - `\"cuda\"`: the CUDA random number generator (GPU only)\n - `\"xla\"`: the XLA random number generator (TPU only)\n - `\"generator\"`: an optional `torch.Generator`\n synchronized_generator (`torch.Generator`, *optional*):\n A random number generator to keep synchronized across processes.\n skip_batches (`int`, *optional*, defaults to 0):\n The number of batches to skip at the beginning.\n kwargs:\n All other keyword arguments to pass to the regular `DataLoader` initialization.\n\n **Available attributes:**\n\n - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.\n Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total\n number of processes\n\n - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.\n \"\"\"\n\n def __init__(\n self,\n dataset,\n device=None,\n rng_types=None,\n synchronized_generator=None,\n skip_batches=0,\n _drop_last: bool = False,\n **kwargs,\n ):\n super().__init__(dataset, **kwargs)\n self.device = device\n self.rng_types = rng_types\n self.synchronized_generator = synchronized_generator\n self.skip_batches = skip_batches\n self.gradient_state = GradientState()\n self._drop_last = _drop_last\n self.iteration = 0\n\n def __iter__(self):\n if self.rng_types is not None:\n synchronize_rng_states(self.rng_types, self.synchronized_generator)\n self.begin()\n\n self.set_epoch(self.iteration)\n dataloader_iter = super().__iter__()\n # We iterate one batch ahead to check when we are at the end\n try:\n current_batch = next(dataloader_iter)\n except StopIteration:\n yield\n\n batch_index = 0\n while True:\n try:\n # But we still move it to the device so it is done before `StopIteration` is reached\n if self.device is not None:\n current_batch = send_to_device(current_batch, self.device)\n next_batch = next(dataloader_iter)\n if batch_index >= self.skip_batches:\n yield current_batch\n batch_index += 1\n current_batch = next_batch\n except StopIteration:\n self.end_of_dataloader = True\n if batch_index >= self.skip_batches:\n yield current_batch\n break\n\n self.iteration += 1\n self.end()\n\n def set_epoch(self, epoch: int):\n # In case it is manually passed in, the user can set it to what they like\n if self.iteration != epoch:\n self.iteration = epoch\n if hasattr(self.batch_sampler, \"sampler\") and hasattr(self.batch_sampler.sampler, \"set_epoch\"):\n self.batch_sampler.sampler.set_epoch(epoch)\n # We support if a custom `Dataset` implementation has `set_epoch`\n # or in general HF datasets `Datasets`\n elif hasattr(self.dataset, \"set_epoch\"):\n self.dataset.set_epoch(epoch)\n\n @property\n def total_batch_size(self):\n batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler\n return (\n batch_sampler.batch_size\n if getattr(batch_sampler, \"split_batches\", False)\n else (batch_sampler.batch_size * getattr(batch_sampler, \"num_processes\", 1))\n )\n\n @property\n def total_dataset_length(self):\n if hasattr(self.dataset, \"total_length\"):\n return self.dataset.total_length\n else:\n return len(self.dataset)\n\n\nif is_tpu_available(check_device=False):\n import torch_xla.distributed.parallel_loader as xpl\n\n class MpDeviceLoaderWrapper(xpl.MpDeviceLoader):\n \"\"\"\n Wrapper for the xpl.MpDeviceLoader class that knows the total batch size.\n\n XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to\n prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main\n thread only.\n\n **Available attributes:**\n\n - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.\n Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total\n number of processes\n\n - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.\n \"\"\"\n\n def __init__(self, dataloader: DataLoaderShard, device: torch.device):\n super().__init__(dataloader, device)\n self._rng_types = self._loader.rng_types\n self._loader.rng_types = None\n\n def __iter__(self):\n if self._rng_types is not None:\n synchronize_rng_states(self._rng_types, self._loader.synchronized_generator)\n\n return super().__iter__()\n\n @property\n def total_batch_size(self):\n return self._loader.total_batch_size\n\n @property\n def total_dataset_length(self):\n return self._loader.total_dataset_length\n\n\nclass DataLoaderDispatcher(DataLoader, DataLoaderStateMixin):\n \"\"\"\n Subclass of a PyTorch `DataLoader` that will iterate and preprocess on process 0 only, then dispatch on each\n process their part of the batch.\n\n Args:\n split_batches (`bool`, *optional*, defaults to `False`):\n Whether the resulting `DataLoader` should split the batches of the original data loader across devices or\n yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of\n `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be\n the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial\n `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch\n size of the `dataloader` is a round multiple of `batch_size`.\n skip_batches (`int`, *optional*, defaults to 0):\n The number of batches to skip at the beginning of an iteration.\n\n **Available attributes:**\n\n - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes.\n Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total\n number of processes\n\n - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes.\n \"\"\"\n\n def __init__(\n self, dataset, split_batches: bool = False, skip_batches=0, _drop_last: bool = False, slice_fn=None, **kwargs\n ):\n shuffle = False\n if is_torch_version(\">=\", \"1.11.0\"):\n from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe\n\n # We need to save the shuffling state of the DataPipe\n if isinstance(dataset, ShufflerIterDataPipe):\n shuffle = dataset._shuffle_enabled\n super().__init__(dataset, **kwargs)\n self.split_batches = split_batches\n if shuffle:\n torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle)\n\n self.gradient_state = GradientState()\n self.state = AcceleratorState()\n self._drop_last = _drop_last\n self.skip_batches = skip_batches\n\n self.slice_fn = slice_tensors if slice_fn is None else slice_fn\n self.iteration = 0\n\n def _fetch_batches(self, iterator):\n batches, batch = None, None\n # On process 0, we gather the batch to dispatch.\n if self.state.process_index == 0:\n try:\n if self.split_batches:\n # One batch of the main iterator is dispatched and split.\n batch = next(iterator)\n else:\n # num_processes batches of the main iterator are concatenated then dispatched and split.\n # We add the batches one by one so we have the remainder available when drop_last=False.\n batches = []\n for _ in range(self.state.num_processes):\n batches.append(next(iterator))\n batch = concatenate(batches, dim=0)\n # In both cases, we need to get the structure of the batch that we will broadcast on other\n # processes to initialize the tensors with the right shape.\n # data_structure, stop_iteration\n batch_info = [get_data_structure(batch), False]\n except StopIteration:\n batch_info = [None, True]\n else:\n batch_info = [None, self._stop_iteration]\n # This is inplace, so after this instruction, every process has the same `batch_info` as process 0.\n broadcast_object_list(batch_info)\n self._stop_iteration = batch_info[1]\n if self._stop_iteration:\n # If drop_last is False and split_batches is False, we may have a remainder to take care of.\n if not self.split_batches and not self._drop_last:\n if self.state.process_index == 0 and len(batches) > 0:\n batch = concatenate(batches, dim=0)\n batch_info = [get_data_structure(batch), False]\n else:\n batch_info = [None, True]\n broadcast_object_list(batch_info)\n return batch, batch_info\n\n def __iter__(self):\n self.begin()\n self.set_epoch(self.iteration)\n main_iterator = None\n if is_torch_version(\">=\", \"2.0.1\"):\n # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts\n # shared seed to all dist processes. Thus, we need to create iterator for all dist processes.\n # But, we only iterate through the DataLoader on process 0.\n main_iterator = super().__iter__()\n elif self.state.process_index == 0:\n main_iterator = super().__iter__()\n stop_iteration = False\n self._stop_iteration = False\n first_batch = None\n next_batch, next_batch_info = self._fetch_batches(main_iterator)\n batch_index = 0\n while not stop_iteration:\n batch, batch_info = next_batch, next_batch_info\n\n if self.state.process_index != 0:\n # Initialize tensors on other processes than process 0.\n batch = initialize_tensors(batch_info[0])\n batch = send_to_device(batch, self.state.device)\n # Broadcast the batch before splitting it.\n batch = broadcast(batch, from_process=0)\n\n if not self._drop_last and first_batch is None:\n # We keep at least num processes elements of the first batch to be able to complete the last batch\n first_batch = self.slice_fn(\n batch,\n slice(0, self.state.num_processes),\n process_index=self.state.process_index,\n num_processes=self.state.num_processes,\n )\n\n if batch is None:\n raise ValueError(\n f\"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration.\"\n )\n\n observed_batch_size = find_batch_size(batch)\n batch_size = observed_batch_size // self.state.num_processes\n\n stop_iteration = self._stop_iteration\n if not stop_iteration:\n # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in\n # the dataloader since the number of batches is a round multiple of the number of processes.\n next_batch, next_batch_info = self._fetch_batches(main_iterator)\n # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them.\n if self._stop_iteration and next_batch_info[0] is None:\n stop_iteration = True\n\n if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0:\n # If the last batch is not complete, let's add the first batch to it.\n batch = concatenate([batch, first_batch], dim=0)\n # Batch size computation above is wrong, it's off by 1 so we fix it.\n batch_size += 1\n\n data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size)\n batch = self.slice_fn(\n batch,\n data_slice,\n process_index=self.state.process_index,\n num_processes=self.state.num_processes,\n )\n\n if stop_iteration:\n self.end_of_dataloader = True\n self.remainder = observed_batch_size\n if batch_index >= self.skip_batches:\n yield batch\n batch_index += 1\n self.iteration += 1\n self.end()\n\n def set_epoch(self, epoch: int):\n # In case it is manually passed in, the user can set it to what they like\n if self.iteration != epoch:\n self.iteration = epoch\n if hasattr(self.batch_sampler.sampler, \"set_epoch\"):\n self.batch_sampler.sampler.set_epoch(epoch)\n elif hasattr(self.dataset, \"set_epoch\"):\n self.dataset.set_epoch(epoch)\n\n def __len__(self):\n whole_length = super().__len__()\n if self.split_batches:\n return whole_length\n elif self._drop_last:\n return whole_length // self.state.num_processes\n else:\n return math.ceil(whole_length / self.state.num_processes)\n\n @property\n def total_batch_size(self):\n return (\n self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes)\n )\n\n @property\n def total_dataset_length(self):\n return len(self.dataset)\n\n\ndef prepare_data_loader(\n dataloader: DataLoader,\n device: Optional[torch.device] = None,\n num_processes: Optional[int] = None,\n process_index: Optional[int] = None,\n split_batches: bool = False,\n put_on_device: bool = False,\n rng_types: Optional[List[Union[str, RNGType]]] = None,\n dispatch_batches: Optional[bool] = None,\n even_batches: bool = True,\n slice_fn_for_dispatch: Optional[Callable] = None,\n) -> DataLoader:\n \"\"\"\n Wraps a PyTorch `DataLoader` to generate batches for one of the processes only.\n\n Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration\n at the first batch that would be too small / not present on all processes or loop with indices from the beginning.\n\n Args:\n dataloader (`torch.utils.data.dataloader.DataLoader`):\n The data loader to split across several devices.\n device (`torch.device`):\n The target device for the returned `DataLoader`.\n num_processes (`int`, *optional*):\n The number of processes running concurrently. Will default to the value given by\n [`~state.AcceleratorState`].\n process_index (`int`, *optional*):\n The index of the current process. Will default to the value given by [`~state.AcceleratorState`].\n split_batches (`bool`, *optional*, defaults to `False`):\n Whether the resulting `DataLoader` should split the batches of the original data loader across devices or\n yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of\n `num_processes` batches at each iteration).\n\n Another way to see this is that the observed batch size will be the same as the initial `dataloader` if\n this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes`\n otherwise.\n\n Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of\n `batch_size`.\n put_on_device (`bool`, *optional*, defaults to `False`):\n Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or\n dictionaries of tensors).\n rng_types (list of `str` or [`~utils.RNGType`]):\n The list of random number generators to synchronize at the beginning of each iteration. Should be one or\n several of:\n\n - `\"torch\"`: the base torch random number generator\n - `\"cuda\"`: the CUDA random number generator (GPU only)\n - `\"xla\"`: the XLA random number generator (TPU only)\n - `\"generator\"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your\n dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.\n\n dispatch_batches (`bool`, *optional*):\n If set to `True`, the datalaoder prepared is only iterated through on the main process and then the batches\n are split and broadcast to each process. Will default to `True` when the underlying dataset is an\n `IterableDataset`, `False` otherwise.\n even_batches (`bool`, *optional*, defaults to `True`):\n If set to `True`, in cases where the total batch size across all processes does not exactly divide the\n dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among\n all workers.\n slice_fn_for_dispatch (`Callable`, *optional*`):\n If passed, this function will be used to slice tensors across `num_processes`. Will default to\n [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be\n ignored otherwise.\n\n Returns:\n `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches\n\n \n\n `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches`\n equal to `False`\n\n \n \"\"\"\n if dispatch_batches is None:\n if not put_on_device:\n dispatch_batches = False\n else:\n dispatch_batches = isinstance(dataloader.dataset, IterableDataset)\n\n if dispatch_batches and not put_on_device:\n raise ValueError(\"Using `dispatch_batches=True` requires `put_on_device=True`.\")\n # Grab defaults from AcceleratorState\n state = AcceleratorState()\n if num_processes is None:\n num_processes = state.num_processes\n if process_index is None:\n process_index = state.process_index\n\n # Sanity check\n if split_batches and dataloader.batch_size > 1 and dataloader.batch_size % num_processes != 0:\n raise ValueError(\n f\"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) \"\n f\"needs to be a round multiple of the number of processes ({num_processes}).\"\n )\n\n new_dataset = dataloader.dataset\n # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it\n new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None\n sampler_is_batch_sampler = False\n synchronized_generator = None\n sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)\n if sampler_is_batch_sampler:\n sampler = getattr(dataloader.sampler, \"sampler\", None)\n else:\n sampler = getattr(dataloader.batch_sampler, \"sampler\", None)\n if isinstance(sampler, RandomSampler):\n # When iterating through the dataloader during distributed processes\n # we want to ensure that on each process we are iterating through the same\n # samples in the same order if a seed is set. This requires a tweak\n # to the `torch.utils.data.RandomSampler` class (if used).\n sampler = SeedableRandomSampler(\n data_source=sampler.data_source,\n replacement=sampler.replacement,\n num_samples=sampler._num_samples,\n generator=getattr(sampler, \"generator\", torch.Generator()),\n )\n\n # No change if no multiprocess\n if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches:\n if isinstance(new_dataset, IterableDataset):\n if getattr(dataloader.dataset, \"generator\", None) is not None:\n synchronized_generator = dataloader.dataset.generator\n new_dataset = IterableDatasetShard(\n new_dataset,\n batch_size=dataloader.batch_size,\n drop_last=dataloader.drop_last,\n num_processes=num_processes,\n process_index=process_index,\n split_batches=split_batches,\n )\n else:\n batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler\n new_batch_sampler = BatchSamplerShard(\n batch_sampler,\n num_processes=num_processes,\n process_index=process_index,\n split_batches=split_batches,\n even_batches=even_batches,\n )\n\n # We ignore all of those since they are all dealt with by our new_batch_sampler\n ignore_kwargs = [\n \"batch_size\",\n \"shuffle\",\n \"sampler\",\n \"batch_sampler\",\n \"drop_last\",\n ]\n\n if rng_types is not None and synchronized_generator is None and \"generator\" in rng_types:\n rng_types.remove(\"generator\")\n\n kwargs = {\n k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])\n for k in _PYTORCH_DATALOADER_KWARGS\n if k not in ignore_kwargs\n }\n\n # Need to provide batch_size as batch_sampler is None for Iterable dataset\n if new_batch_sampler is None:\n kwargs[\"drop_last\"] = dataloader.drop_last\n kwargs[\"batch_size\"] = (\n dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size\n )\n if isinstance(sampler, SeedableRandomSampler):\n if sampler_is_batch_sampler:\n dataloader.sampler.sampler = sampler\n else:\n dataloader.batch_sampler.sampler = sampler\n if dispatch_batches:\n kwargs.pop(\"generator\")\n dataloader = DataLoaderDispatcher(\n new_dataset,\n split_batches=split_batches,\n batch_sampler=new_batch_sampler,\n _drop_last=dataloader.drop_last,\n slice_fn=slice_fn_for_dispatch,\n **kwargs,\n )\n elif sampler_is_batch_sampler:\n dataloader = DataLoaderShard(\n new_dataset,\n device=device if put_on_device and state.distributed_type != DistributedType.TPU else None,\n sampler=new_batch_sampler,\n batch_size=dataloader.batch_size,\n rng_types=rng_types,\n _drop_last=dataloader.drop_last,\n synchronized_generator=synchronized_generator,\n **kwargs,\n )\n else:\n dataloader = DataLoaderShard(\n new_dataset,\n device=device if put_on_device and state.distributed_type != DistributedType.TPU else None,\n batch_sampler=new_batch_sampler,\n rng_types=rng_types,\n synchronized_generator=synchronized_generator,\n _drop_last=dataloader.drop_last,\n **kwargs,\n )\n\n if state.distributed_type == DistributedType.TPU:\n return MpDeviceLoaderWrapper(dataloader, device)\n return dataloader\n\n\nclass SkipBatchSampler(BatchSampler):\n \"\"\"\n A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`.\n \"\"\"\n\n def __init__(self, batch_sampler, skip_batches=0):\n self.batch_sampler = batch_sampler\n self.skip_batches = skip_batches\n\n def __iter__(self):\n for index, samples in enumerate(self.batch_sampler):\n if index >= self.skip_batches:\n yield samples\n\n @property\n def total_length(self):\n return len(self.batch_sampler)\n\n def __len__(self):\n return len(self.batch_sampler) - self.skip_batches\n\n\nclass SkipDataLoader(DataLoader):\n \"\"\"\n Subclass of a PyTorch `DataLoader` that will skip the first batches.\n\n Args:\n dataset (`torch.utils.data.dataset.Dataset`):\n The dataset to use to build this datalaoder.\n skip_batches (`int`, *optional*, defaults to 0):\n The number of batches to skip at the beginning.\n kwargs:\n All other keyword arguments to pass to the regular `DataLoader` initialization.\n \"\"\"\n\n def __init__(self, dataset, skip_batches=0, **kwargs):\n super().__init__(dataset, **kwargs)\n self.skip_batches = skip_batches\n\n def __iter__(self):\n for index, batch in enumerate(super().__iter__()):\n if index >= self.skip_batches:\n yield batch\n\n\ndef skip_first_batches(dataloader, num_batches=0):\n \"\"\"\n Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`.\n \"\"\"\n dataset = dataloader.dataset\n sampler_is_batch_sampler = False\n if isinstance(dataset, IterableDataset):\n new_batch_sampler = None\n else:\n sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler)\n batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler\n new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches)\n\n # We ignore all of those since they are all dealt with by our new_batch_sampler\n ignore_kwargs = [\n \"batch_size\",\n \"shuffle\",\n \"sampler\",\n \"batch_sampler\",\n \"drop_last\",\n ]\n\n kwargs = {\n k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k])\n for k in _PYTORCH_DATALOADER_KWARGS\n if k not in ignore_kwargs\n }\n\n # Need to provide batch_size as batch_sampler is None for Iterable dataset\n if new_batch_sampler is None:\n kwargs[\"drop_last\"] = dataloader.drop_last\n kwargs[\"batch_size\"] = dataloader.batch_size\n\n if isinstance(dataloader, DataLoaderDispatcher):\n if new_batch_sampler is None:\n # Need to manually skip batches in the dataloader\n kwargs[\"skip_batches\"] = num_batches\n dataloader = DataLoaderDispatcher(\n dataset,\n split_batches=dataloader.split_batches,\n batch_sampler=new_batch_sampler,\n _drop_last=dataloader._drop_last,\n **kwargs,\n )\n elif isinstance(dataloader, DataLoaderShard):\n if new_batch_sampler is None:\n # Need to manually skip batches in the dataloader\n kwargs[\"skip_batches\"] = num_batches\n elif sampler_is_batch_sampler:\n kwargs[\"sampler\"] = new_batch_sampler\n kwargs[\"batch_size\"] = dataloader.batch_size\n else:\n kwargs[\"batch_sampler\"] = new_batch_sampler\n dataloader = DataLoaderShard(\n dataset,\n device=dataloader.device,\n rng_types=dataloader.rng_types,\n synchronized_generator=dataloader.synchronized_generator,\n **kwargs,\n )\n else:\n if new_batch_sampler is None:\n # Need to manually skip batches in the dataloader\n dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs)\n else:\n dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs)\n\n return dataloader\n","repo_name":"huggingface/accelerate","sub_path":"src/accelerate/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":44813,"program_lang":"python","lang":"en","doc_type":"code","stars":6032,"dataset":"github-code","pt":"85"} +{"seq_id":"35749634247","text":"import logging\nimport re\nimport time\nimport unittest\nimport warnings\n\nimport numpy\n\nfrom odemis import model\nfrom odemis.acq import stream\nfrom odemis.acq.drift import AnchoredEstimator\nfrom odemis.acq.leech import AnchorDriftCorrector, ProbeCurrentAcquirer\nfrom odemis.driver import simsem\n\nlogging.getLogger().setLevel(logging.DEBUG)\n\nclass Fake0DDetector(model.Detector):\n \"\"\"\n Imitates a probe current detector, but you need to send the data yourself (using\n comp.data.notify(d)\n \"\"\"\n def __init__(self, name):\n model.Detector.__init__(self, name, \"fakedet\", parent=None)\n self.data = Fake0DDataFlow()\n self._shape = (float(\"inf\"),)\n\n\nclass Fake0DDataFlow(model.DataFlow):\n \"\"\"\n Mock object just sufficient for the ProbeCurrentAcquirer\n \"\"\"\n def get(self):\n da = model.DataArray([1e-12], {model.MD_ACQ_DATE: time.time()})\n return da\n\n\nCONFIG_SED = {\"name\": \"sed\", \"role\": \"sed\"}\nCONFIG_SCANNER = {\"name\": \"scanner\", \"role\": \"ebeam\"}\nCONFIG_SEM = {\"name\": \"sem\", \"role\": \"sem\", \"image\": \"simsem-fake-output.h5\",\n \"drift_period\": 0.1,\n \"children\": {\"detector0\": CONFIG_SED, \"scanner\": CONFIG_SCANNER}\n }\n\n\nclass ADCTestCase(unittest.TestCase):\n\n def setUp(self):\n # Ignore RuntimeWarning: numpy.ndarray size changed, may indicate binary incompatibility.\n # Expected 80 from C header, got 88 from PyObject\n # This warning is not caused by the code explicitly changing the array size but rather\n # by an inconsistency between different versions of NumPy.\n warnings.filterwarnings(\n \"ignore\", category=RuntimeWarning, message=re.escape(\"numpy.ndarray size changed\")\n )\n\n @classmethod\n def setUpClass(cls):\n cls.sem = simsem.SimSEM(**CONFIG_SEM)\n\n for child in cls.sem.children.value:\n if child.name == CONFIG_SED[\"name\"]:\n cls.sed = child\n elif child.name == CONFIG_SCANNER[\"name\"]:\n cls.scanner = child\n\n def test_set_roi(self):\n dc = AnchorDriftCorrector(self.scanner, self.sed)\n\n # Too small => should grow a little\n dc.roi.value = (0.1, 0.1, 0.1, 0.1)\n roi = tuple(dc.roi.value)\n self.assertGreater(roi[2] - roi[0], 0)\n self.assertGreater(roi[3] - roi[1], 0)\n\n # Set the same small value => no change\n dc.roi.value = tuple(roi)\n self.assertEqual(roi, dc.roi.value)\n\n # Full FoV => allowed\n dc.roi.value = (0, 0, 1, 1)\n self.assertEqual(dc.roi.value, (0, 0, 1, 1))\n\n # UNDEFINED_ROI doesn't allow to start\n dc.roi.value = stream.UNDEFINED_ROI\n self.assertEqual(dc.estimateAcquisitionTime(0.1, (4, 3)), 0)\n with self.assertRaises(ValueError):\n dc.series_start()\n\n def test_estimateAcquisitionTime(self):\n \"\"\"\n Tests the minimum time required to acquire one anchor area\n \"\"\"\n # Total anchor estimation time should be more than 0\n dc = AnchorDriftCorrector(self.scanner, self.sed)\n dc.roi.value = (0, 0, 0.1, 0.1)\n dce = AnchoredEstimator(dc._scanner, dc._detector,\n dc.roi.value, dc.dwellTime.value)\n test_time = dce.estimateAcquisitionTime()\n total_anchor_estimation = dc.estimateAcquisitionTime(0.1, (5, 5))\n self.assertGreaterEqual(total_anchor_estimation, test_time)\n\n def test_get_next_pixels(self):\n # TODO dc.series_start, dc.complete, dc.series_complete needs to be tested\n dc = AnchorDriftCorrector(self.scanner, self.sed)\n\n # Period = dt => every pixel\n dc.roi.value = (0, 0, 0.1, 0.1)\n dc.dwellTime.value = dc.dwellTime.range[0]\n dc.period.value = 0.1\n dc.series_start()\n np = dc.start(0.1, (5, 5))\n scan_px = np\n while scan_px < 5 * 5:\n self.assertEqual(np, 1) # don't check the last call\n np = dc.next([None])\n scan_px += np\n dc.next([None]) # one last time\n\n dc.complete([None])\n dc.series_complete([None])\n\n # Period = 2.5 * dt => alternatively every 2 and 3 pixels\n dc.period.value = 0.1 * 2.5\n dc.series_start()\n np = dc.start(0.1, (5, 5))\n scan_px = np\n while scan_px < 5 * 5:\n self.assertIn(np, (2, 3)) # don't check the last call\n np = dc.next([None])\n scan_px += np\n dc.next([None]) # one last time\n\n dc.complete([None])\n dc.series_complete([None])\n\n\n# @skip(\"simple\")\nclass PCAcquirerTestCase(unittest.TestCase):\n\n def test_get_next_pixels(self):\n det = Fake0DDetector(\"test\")\n pca = ProbeCurrentAcquirer(det)\n\n # Period = dt => every pixel\n pca.period.value = 0.1\n np = pca.start(0.1, (10, 10))\n scan_px = np\n while scan_px < 10 * 10:\n self.assertEqual(np, 1) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n pca.next([da]) # one last time\n\n # Period = dt + epsilon => every pixel\n pca.period.value = 0.10001\n np = pca.start(0.1, (10, 10))\n scan_px = np\n while scan_px < 10 * 10:\n self.assertEqual(np, 1) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n pca.next([da]) # one last time\n\n # Period < dt => every pixel\n pca.period.value = 0.05\n np = pca.start(0.1, (10, 10))\n scan_px = np\n while scan_px < 10 * 10:\n self.assertEqual(np, 1) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n pca.next([da]) # one last time\n\n # Period = 2.5 * dt => alternatively every 2 and 3 pixels\n pca.period.value = 0.1 * 2.5\n np = pca.start(0.1, (10, 10))\n scan_px = np\n while scan_px < 10 * 10:\n self.assertIn(np, (2, 3)) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n pca.next([da]) # one last time\n\n # Period = dt * 5 => every 5 px\n pca.period.value = 0.5\n np = pca.start(0.1, (10, 10))\n scan_px = np\n while scan_px < 10 * 10:\n self.assertEqual(np, 5) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n pca.next([da]) # one last time\n\n # Period > dt * shape => at first and last\n pca.period.value = 100\n np = pca.start(0.1, (10, 10))\n scan_px = np\n while scan_px < 10 * 10:\n self.assertEqual(np, 10 * 10) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n pca.next([da]) # one last time\n\n # Period = dt * shape / 2 => at first, middle and last\n pca.period.value = 0.1 * 10 * 5\n np = pca.start(0.1, (10, 10))\n scan_px = np\n while scan_px < 10 * 10:\n self.assertEqual(np, 10 * 10 / 2) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n pca.next([da]) # one last time\n\n # Short period, on a large shape\n pca.period.value = 4900e-6 # A little less than every 10 lines\n np = pca.start(1e-6, (700, 500))\n assert 9 * 500 <= np <= 4900\n scan_px = np\n while scan_px < 700 * 500:\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n left = 700 * 500 - scan_px\n if left < 4900:\n assert np <= left\n else:\n assert 9 * 500 <= np <= 4900\n scan_px += np\n pca.next([da]) # one last time\n\n def test_complete(self):\n det = Fake0DDetector(\"test\")\n pca = ProbeCurrentAcquirer(det)\n\n # Period = dt * shape / 2 => at first, middle and last\n pca.period.value = 0.1 * 4 * 6 / 2\n np = pca.start(0.1, (4, 6))\n scan_px = np\n while scan_px < 4 * 6:\n self.assertEqual(np, 4 * 6 / 2) # don't check the last call\n da = model.DataArray([0] * np, {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n scan_px += np\n np = pca.next([da])\n\n # Should add the metadata to the acquisition\n da = model.DataArray([0] * 4 * 6, {model.MD_ACQ_DATE: time.time()})\n pca.complete([da])\n\n cot = da.metadata[model.MD_EBEAM_CURRENT_TIME]\n self.assertEqual(len(cot), 3)\n # Dates should be ordered\n assert cot[0][0] < cot[1][0] < cot[2][0]\n # Data should be small\n assert 0 < cot[0][1] < 1e-3\n\n def test_shape_1(self):\n \"\"\"\n When the shape is just (1), a single acquisition\n \"\"\"\n det = Fake0DDetector(\"test\")\n pca = ProbeCurrentAcquirer(det)\n\n # Period longer than the acquisition => just before and after\n pca.period.value = 1\n np = pca.start(0.1, (1,))\n self.assertEqual(np, 1)\n da = model.DataArray(numpy.ones((230, 42)), {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n\n # Should add the metadata to the acquisition\n pca.complete([da])\n cot = da.metadata[model.MD_EBEAM_CURRENT_TIME]\n self.assertEqual(len(cot), 2)\n # Dates should be ordered\n assert cot[0][0] < cot[1][0]\n # Data should be small\n assert 0 < cot[0][1] < 1e-3\n\n # Period shorter than the acquisition, but only one pixel, so just\n # before and after too\n pca.period.value = 0.1\n np = pca.start(1, (1,))\n self.assertEqual(np, 1)\n da = model.DataArray(numpy.ones((230, 42)), {model.MD_ACQ_DATE: time.time()})\n np = pca.next([da])\n\n # Should add the metadata to the acquisition\n pca.complete([da])\n cot = da.metadata[model.MD_EBEAM_CURRENT_TIME]\n self.assertEqual(len(cot), 2)\n # Dates should be ordered\n assert cot[0][0] < cot[1][0]\n # Data should be small\n assert 0 < cot[0][1] < 1e-3\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"delmic/odemis","sub_path":"src/odemis/acq/test/leech_test.py","file_name":"leech_test.py","file_ext":"py","file_size_in_byte":10647,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"85"} +{"seq_id":"13632758217","text":"if __name__ == '__main__':\n N = int(input())\n arr = []\n for _ in range(N):\n c = input().split()\n met, args = c[0], c[1:]\n \n if met != 'print':\n expression = f\"{met}({','.join(args)})\"\n eval(f'arr.{expression}')\n else: \n print(arr)\n \n","repo_name":"ball0803/Monkey-together-strong","sub_path":"Euros Cake/Hackerrank/02. basic datatype/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70450289238","text":"from math import floor\nimport numpy as np\n\nA = np.array([[1, -2, 2],\n [2, -1, 2],\n [2, -2, 3]])\n\nB = np.array([[1, 2, 2],\n [2, 1, 2],\n [2, 2, 3]])\n\nC = np.array([[-1, 2, 2],\n [-2, 1, 2],\n [-2, 2, 3]])\n\n# Generate first [3^(d+1)-1]/2 primitive pythagorean triples\n# i.e. generates ternary tree of depth d\ndef primitive_pythag_triples(d):\n max_size = floor(3**(d+1)-1)/2\n triples = []\n triples_at_current_d = [[3, 4, 5]]\n\n while len(triples) < max_size:\n for triple in triples_at_current_d:\n triples_at_d_plus_one = []\n\n triples_at_d_plus_one.append(np.matmul(A, triple).tolist())\n triples_at_d_plus_one.append(np.matmul(B, triple).tolist())\n triples_at_d_plus_one.append(np.matmul(C, triple).tolist())\n\n triples.extend(triples_at_current_d)\n triples_at_current_d = triples_at_d_plus_one\n\n return triples\n\n# Naive function to return divisors of n\ndef divisors(n):\n divs = []\n\n for i in range(1, n//2 + 1):\n if n % i == 0:\n divs.append(i)\n\n return divs\n\ntriple_sums = {}\n\n# Only use triples from pythag triple tree up to a depth of 3 since\n# all triples of depth > 3 sum to more than 1000\nfor triple in primitive_pythag_triples(3):\n\n triple_sum = sum(triple)\n\n if triple_sum < 1000:\n if triple_sum in triple_sums:\n triple_sums[triple_sum] += 1\n else:\n triple_sums[triple_sum] = 1\n\n# Find all divisors of a number then sum number of primitive triples that sum to each divisor\nlargest_no_triples = 0\nnum_with_largest_no_triples = 0\n\nfor num in triple_sums:\n new_no_triples = triple_sums[num]\n divs = divisors(num)\n\n for d in divs:\n if d in triple_sums:\n new_no_triples += triple_sums[d]\n\n if new_no_triples > largest_no_triples:\n largest_no_triples = new_no_triples\n num_with_largest_no_triples = num\n\nprint(num_with_largest_no_triples)","repo_name":"Dervillay/Project_Euler","sub_path":"problem_39.py","file_name":"problem_39.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23819029543","text":"n = int(input())\n\nls = list(map(int, input().split()))\n\nd = [1] * n\n\nfor i in range(1, n):\n for j in range(i, -1, -1):\n if ls[j] < ls[i]:\n d[i] = max(d[i], d[j] + 1)\n\nprint(max(d))","repo_name":"juhan-y/Algorithm_Study","sub_path":"윤주한/백준6주차/11053.py","file_name":"11053.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"15568901860","text":"import sys\nimport logging\nimport datetime\n\n#Gets the current date for use in logging.\ndate_string = str(datetime.date.today()).replace('-','_')\n\n#define loggers\nbot_function_logger = logging.getLogger('botfunctions')\ncommand_logger = logging.getLogger('commands')\nquery_logger = logging.getLogger('queries')\nviewer_logger = logging.getLogger('viewer')\nstreamer_logger = logging.getLogger('streamer')\ngame_logger = logging.getLogger('games')\n\n#define file handlers\nbf_file_handler = logging.FileHandler(f'Chatbot\\logs\\{date_string}_Log.log')\nc_file_handler = logging.FileHandler(f'Chatbot\\logs\\{date_string}_Log.log')\nq_file_handler = logging.FileHandler(f'Chatbot\\logs\\{date_string}_Log.log')\nv_file_handler = logging.FileHandler(f'Chatbot\\logs\\{date_string}_Log.log')\ns_file_handler = logging.FileHandler(f'Chatbot\\logs\\{date_string}_Log.log')\ng_file_handler = logging.FileHandler(f'Chatbot\\logs\\{date_string}_Log.log')\n\n#define stream handlers\nbf_stream_handler = logging.StreamHandler(sys.stdout)\nc_stream_handler = logging.StreamHandler(sys.stdout)\nq_stream_handler = logging.StreamHandler(sys.stdout)\nv_stream_handler = logging.StreamHandler(sys.stdout)\ns_stream_handler = logging.StreamHandler(sys.stdout)\ng_stream_handler = logging.StreamHandler(sys.stdout)\n\n#set formatters\nformatter = logging.Formatter('%(asctime)s\\t%(name)s\\t%(levelname)s\\t%(lineno)d\\t%(message)s')\n\n#set formatter to handlers\nbf_file_handler.setFormatter(formatter)\nbf_stream_handler.setFormatter(formatter)\nc_file_handler.setFormatter(formatter)\nc_stream_handler.setFormatter(formatter)\nq_file_handler.setFormatter(formatter)\nq_stream_handler.setFormatter(formatter)\nv_file_handler.setFormatter(formatter)\nv_stream_handler.setFormatter(formatter)\ns_file_handler.setFormatter(formatter)\ns_stream_handler.setFormatter(formatter)\ng_file_handler.setFormatter(formatter)\ng_stream_handler.setFormatter(formatter)\n\n#set handlers to loggers\nbot_function_logger.addHandler(bf_file_handler)\ncommand_logger.addHandler(c_file_handler)\ncommand_logger.addHandler(c_stream_handler)\nquery_logger.addHandler(q_file_handler)\nviewer_logger.addHandler(v_file_handler)\nstreamer_logger.addHandler(v_file_handler)\ngame_logger.addHandler(g_file_handler)\n\n#set logging levels\nbot_function_logger.setLevel(10)\ncommand_logger.setLevel(10)\nquery_logger.setLevel(10)\nviewer_logger.setLevel(10)\nstreamer_logger.setLevel(10)\ngame_logger.setLevel(10)","repo_name":"RJsam3/Python-Chatbot","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"37332451772","text":"## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION]\r\n## ALL RIGHTS RESERVED.\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## Neither the name of the SONATA-NFV, 5GTANGO [, ANY ADDITIONAL AFFILIATION]\r\n## nor the names of its contributors may be used to endorse or promote\r\n## products derived from this software without specific prior written\r\n## permission.\r\n##\r\n## This work has been performed in the framework of the SONATA project,\r\n## funded by the European Commission under Grant number 671517 through\r\n## the Horizon 2020 and 5G-PPP programmes. The authors would like to\r\n## acknowledge the contributions of their colleagues of the SONATA\r\n## partner consortium (www.sonata-nfv.eu).\r\n##\r\n## This work has been performed in the framework of the 5GTANGO project,\r\n## funded by the European Commission under Grant number 761493 through\r\n## the Horizon 2020 and 5G-PPP programmes. The authors would like to\r\n## acknowledge the contributions of their colleagues of the 5GTANGO\r\n## partner consortium (www.5gtango.eu).\r\n\r\n\r\nimport logging, os, yaml, json, errno, requests, functools, time\r\nfrom logging.handlers import RotatingFileHandler\r\nfrom flask import Flask, Blueprint, jsonify, request, Response,json, make_response\r\nfrom decsup.inouttransforms import InOutTransforms as iotran\r\nfrom flask_restplus import Api, Resource\r\nfrom decsup.db_models.models import MongoDB as mongo\r\nfrom decsup.word2vec import TrainModel as rec_mod\r\nimport pandas as pd\r\nfrom decsup.logger import TangoLogger as TangoLogger\r\n\r\n\r\n\r\n\r\nTrn_mod = mongo(collection='trained_model')\r\ndict_db = mongo(collection='dict_users')\r\n\r\nrec_mod = rec_mod()\r\nioObj = iotran()\r\ntrain_bool = 0 # this needs to start with 0\r\n\r\napp = Flask(__name__)\r\nblueprint = Blueprint('api', __name__, url_prefix='/api')\r\napi = Api(blueprint, version=\"0.1\",\r\n title='5GTANGO tng-dec-sup API',\r\n description=\"5GTANGO tng-dec-sup REST API to recommendations.\")\r\napp.register_blueprint(blueprint)\r\n\r\n# LOG = logging.getLogger('logger')\r\n# LOG.setLevel(logging.DEBUG)\r\nLOG = TangoLogger.getLogger(__name__)\r\n\r\ndef catch_exception(f):\r\n @functools.wraps(f)\r\n def func(*args,**kwargs):\r\n try:\r\n return f(*args,**kwargs)\r\n except ValueError as e:\r\n print('Caught an exception in',f.__name__)\r\n\r\n return func\r\n\r\n\r\n@api.route('/tests//', methods =['POST'])\r\nclass TangoDsm(Resource):\r\n\r\n def post(self, user=None, test_id=None):\r\n global train_bool\r\n start_time =time.time()\r\n LOG.info(\"Insertion of new selection of user {} with test {}\".format(user, test_id),\r\n extra={\"start_stop\": \"START\"})\r\n try:\r\n user_ins = dict_db.insert_user(user, test_id)\r\n except Exception as e:\r\n LOG.error(e, extra={\"status\": 400, \"time_elapsed\": \"%.3f seconds\" % (time.time() - start_time)})\r\n return ioObj.generic_resp(400, 'application/json', ioObj.json_d(ioObj.error_message(e)))\r\n train_bool = 1\r\n LOG.info(\"Insertion of new selection of user {x} with test {y}\".format(x=user, y=test_id),\r\n extra={ \"status\": 200, \"time_elapsed\": \"%.3f seconds\" % (time.time() - start_time)})\r\n return ioObj.generic_resp(200,'application/json',\r\n ioObj.json_d(ioObj.success_message(\"Stored user {x} with test {y}\".format(x=user, y=test_id))))\r\n\r\n\r\n\r\n@api.route('/users/',methods=[ 'GET', 'DELETE' ])\r\nclass TangoDsmUsers(Resource):\r\n\r\n def get(self, user):\r\n global train_bool\r\n start_time = time.time()\r\n LOG.info(\"Recommendations of user {}\".format(user),\r\n extra={\"start_stop\": \"START\"})\r\n try:\r\n user_exists = dict_db.find_user_bool(user)\r\n if not user_exists:\r\n LOG.error(\"User {} not found\".format(user)\r\n ,extra={\"status\": 404,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(404,'application/json',\r\n ioObj.json_d(\r\n ioObj.error_message(\"User {x} not found\".format(x=user))))\r\n except Exception as e:\r\n LOG.error(e ,extra={\"status\": 500,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(500,'application/json',\r\n ioObj.json_d(\r\n ioObj.error_message(e)))\r\n n = request.args.get('n',default=2,type=int)\r\n file = Trn_mod.get_model_metadata(rec_mod.filename)\r\n if train_bool == 1:\r\n LOG.debug(\"Predictions from recommendation engine with re-train\")\r\n pd_users = pd.DataFrame.from_dict(dict_db.find_users())\r\n rec_mod.train_mod(pd_users, item_col='item', rating_col='rating', user_col='user')\r\n if Trn_mod.check_exist_model(rec_mod.filename):\r\n Trn_mod.find_delete_model(file['_id'])\r\n Trn_mod.find_delete_model_metadata(rec_mod.filename)\r\n predictions, results = rec_mod.get_user_pred(user_id=user, dataframe=pd_users, item_col='item', rating_col='rating', user_col='user', n=n)\r\n rec_mod.dump_model(predictions)\r\n model_id = Trn_mod.insert_grid(rec_mod.filename)\r\n Trn_mod.insert_model_metadata(model_id, rec_mod.filename)\r\n train_bool = 0\r\n LOG.info(\"Recommendations of user {} =\".format(user) + str(ioObj.json_d(results)),\r\n extra={\"status\": 200,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(200, 'application/json', ioObj.json_d(ioObj.success_message(results)))\r\n else:\r\n LOG.debug(\"Predictions from same recommendation engine without re-train\")\r\n Trn_mod.load_grid(file['_id'], rec_mod.filename)\r\n predictions, _ = rec_mod.load_model()\r\n results = rec_mod.get_user_pred_stable(user, predictions, n=n)\r\n LOG.info(\"Recommendations of user {} =\".format(user) + str(ioObj.json_d(results)),\r\n extra={\"status\": 200,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(200, 'application/json', ioObj.json_d(ioObj.success_message(results)))\r\n\r\n def delete(self, user):\r\n start_time = time.time()\r\n try:\r\n new_dict, occurrences = dict_db.delete_user(delete_item=user, array='user')\r\n if occurrences == 0:\r\n LOG.error(\"User {} not found\".format(user)\r\n ,extra={\"status\": 404,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(404,'application/json',\r\n ioObj.json_d(\r\n ioObj.error_message(\"User {x} not found\".format(x=user))))\r\n except TypeError:\r\n LOG.error(\"User {} not found due to DB problem\".format(user)\r\n ,extra={\"status\": 404,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(404,'application/json',\r\n ioObj.json_d(\r\n ioObj.error_message(\"User {x} not found due to DB problem\".format(x=user))))\r\n\r\n dict_db.delete_dictuser()\r\n dict_db.insert_dictuser(new_dict)\r\n\r\n LOG.info(\"User {} deleted with {} occurrences\".format(user,occurrences),\r\n extra={\"status\": 200,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(200,'application/json',\r\n ioObj.json_d(ioObj.success_message(\"User {} deleted with {} occurrences\".format(user, occurrences))))\r\n\r\n\r\n@api.route('/tests/', methods=['DELETE'])\r\nclass TangoDsmTestsID(Resource):\r\n\r\n def delete(self, item_id):\r\n start_time = time.time()\r\n try:\r\n new_dict, occurrences = dict_db.delete_user(delete_item=item_id, array='item')\r\n if occurrences == 0:\r\n LOG.error(\"Item {} not found\".format(item_id)\r\n ,extra={\"status\": 404,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(404,'application/json',\r\n ioObj.json_d(\r\n ioObj.error_message(\"Item {x} not found\".format(x=item_id))))\r\n except TypeError as e:\r\n LOG.error(\"Item {} not found due to DB problem\".format(item_id),\r\n extra={\"status\": 404,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(404, 'application/json',\r\n ioObj.json_d(\r\n ioObj.error_message(\"Item {x} not found due to DB problem\".format(x=item_id))))\r\n dict_db.delete_dictuser()\r\n dict_db.insert_dictuser(new_dict)\r\n\r\n LOG.info(\"Item {} deleted with {} occurrences\".format(item_id,occurrences),\r\n extra={\"status\": 200,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(200,'application/json',\r\n ioObj.json_d(ioObj.success_message(\r\n \"Item {} deleted with {} occurrences\".format(item_id,occurrences))))\r\n\r\n@api.route('/tests', methods=['GET'])\r\nclass TangoDsmTests(Resource):\r\n def get(self):\r\n start_time = time.time()\r\n try:\r\n dict_users = dict_db.get_dict()\r\n except TypeError:\r\n LOG.error(\"Recommender vector not found due to DB problem\"\r\n ,extra={\"status\": 404,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(404,'application/json',\r\n ioObj.json_d(\r\n ioObj.error_message(\"Recommender vector not found due to DB problem\")))\r\n\r\n LOG.info(\"Recommender vector found\",\r\n extra={\"status\": 200,\"time_elapsed\": \"%.3f seconds\" % (time.time()-start_time)})\r\n return ioObj.generic_resp(200, 'application/json',\r\n ioObj.json_d(dict_users))\r\n\r\ndef mkdir_p(path):\r\n try:\r\n os.makedirs(path, exist_ok=True) # Python>3.2\r\n except TypeError:\r\n try:\r\n os.makedirs(path)\r\n except OSError as exc: # Python >2.5\r\n if exc.errno == errno.EEXIST and os.path.isdir(path):\r\n pass\r\n else: raise\r\n\r\n\r\nclass MakeFileHandler(RotatingFileHandler):\r\n def __init__(self, filename, maxBytes, backupCount, mode='a', encoding=None, delay=0):\r\n mkdir_p(os.path.dirname(filename))\r\n RotatingFileHandler.__init__(self, filename,maxBytes, backupCount )\r\n\r\n\r\nif __name__ == '__main__':\r\n app.debug=True\r\n # handler = MakeFileHandler ( 'logs/logger' , maxBytes=10000 , backupCount=1 )\r\n # handler.setLevel ( logging.DEBUG )\r\n # app.logger.addHandler ( handler )\r\n # log = logging.getLogger('werkzeug')\r\n # log.setLevel(logging.INFO)\r\n # log.addHandler(handler)\r\n app.run(host='0.0.0.0', port=os.getenv('PORT',5000))\r\n","repo_name":"panstav1/tng-dsm","sub_path":"src/decsup/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1699802383","text":"from collections import defaultdict\nclass Solution(object):\n def countComponents(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: int\n \"\"\"\n def visit(ed, u):\n if u in ed:\n to_v = ed[u]\n ed.pop(u)\n for v in to_v:\n visit(ed, v)\n ed = defaultdict(list)\n for u, v in edges:\n ed[u].append(v)\n ed[v].append(u)\n sing, cnt = n - len(ed), 0\n while ed.keys():\n visit(ed, ed.keys()[0])\n cnt += 1\n return cnt + sing","repo_name":"coolmich/py-leetcode","sub_path":"solu/323. Number of Connected Components in an Undirected Graph.py","file_name":"323. Number of Connected Components in an Undirected Graph.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"3852281279","text":"from sys import stdin\n\ndef prime(n):\n a=0\n if n==1:\n a+=1\n elif n==2:\n a+=1\n elif n==3:\n a+=1\n elif n==5:\n a+=1\n else:\n if n%2==0:\n a+=0\n elif n%3==0:\n a+=0\n elif n%5==0:\n a+=0\n elif n%3!=0:\n a+=1\n else:\n return prime(n-1)\n return a\n\ndef main():\n n=[int(i) for i in stdin.readline().strip().split(',')]\n z=0\n for j in n:\n z+=prime(j)\n print(\"Number of primes in the list:\",z)\n\nmain()\n \n\n \n","repo_name":"Nikolas2001-13/Universidad","sub_path":"Nikolas_ECI_182/PIMB-2/W81.py","file_name":"W81.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"24310470949","text":"N = int(input())\nresult = 0\n\nwhile N >= 0 :\n if N%5 == 0 :\n result += N//5\n break\n N -= 3\n result += 1\nelse :\n result = -1\n\nprint(result)\n\n\n# N은 설탕의 무게를 초기값으로 한 데이터이다.\n# N을 5로 나눈 나머지가 0이라면 봉지개수 result에 N을 5로 나눈 몫이 들어가고 \n# while 문이 끝난다.\n# 만약 나머지가 0이 아니라면 N에서 3을 빼고 result 에 1을 더한 뒤\n# 다시 while 문을 돌려 3이 빠진 만큼의 N을 5로 나누길 반복한다.\n# 이는 5로 전부 나누어지지 않았을 시 설탕에서 3만큼을 3짜리 봉지 하나에 넣고\n# 다시 5짜리 봉지에 나누어넣어보길 반복하는 행동을 의미한다.\n\n# while 문을 반복하다가 N값이 음수가 된다면 문제에서 요청한대로 -1을 result에 넣어준다.\n","repo_name":"jjubbu/baekjoon-algorithm","sub_path":"python/2839.py","file_name":"2839.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12439162088","text":"\nfrom status_objects.generic_status import GenericStatus\n\n\n# f = open(\"example.txt\", \"r\")\n# text = f.read()\n# response_as_dict = json.loads(text)\n# f.close()\n\nclass Slack(GenericStatus):\n def __init__(self):\n link = 'https://status.slack.com/api/v2.0.0/current'\n super().__init__(\"Slack\", link)\n response_as_dict = self.get_status_endpoint_response()\n\n found_status = response_as_dict['status']\n if found_status == 'ok':\n self.set_status_ok()\n else:\n self.set_status_incident()\n self.detail = \"detail\"\n","repo_name":"Jfeather4/dashboard","sub_path":"status_objects/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34418867035","text":"def mygenerator():\n print('First item')\n yield 10\n\n # return\n\n print('Second item')\n yield 20\n\n print('Last item')\n yield 30\n\n\ngen = mygenerator()\n\nnext(gen)\nnext(gen)\nnext(gen)\n\n\ndef get_sequence_upto(x):\n for i in range(x):\n yield i\n\n\ngen=get_sequence_upto(5)\nwhile True:\n try:\n print(\"Received on next(): \", next(gen))\n except StopIteration:\n break\n","repo_name":"silasmj/python_sessions","sub_path":"generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3291523873","text":"from fastapi import FastAPI, HTTPException, status, Request\nfrom fastapi.responses import JSONResponse\n\n\nclass UnicornException(Exception):\n def __init__(self, name: str):\n self.name = name\n\n\napp = FastAPI()\n\n\n@app.exception_handler(UnicornException)\nasync def unicorn_exception_handler(req: Request, exc: UnicornException):\n return JSONResponse(\n status_code = status.HTTP_418_IM_A_TEAPOT,\n content={\"message\": f\"Oops! {exc.name} did something. There goes a rainbow...\",},\n )\n\n\nitems = {\"foo\": \"The Foo Wrestlers\"}\n\n\n@app.get(\"/items/{item_id}\")\nasync def get_item(item_id: str):\n if item_id not in items:\n raise HTTPException(\n status_code=404,\n detail=\"Item not found\",\n headers={\"X-Error\": \"There goes my error\"})\n return items[item_id]\n\n\n@app.get(\"/unicorns/{name}\")\nasync def get_unicorn(name: str):\n if name == \"yolo\":\n raise UnicornException(name=name)\n return {\"unicorn_name\": name}","repo_name":"0Zyablik0/Web-Lerning","sub_path":"FastAPI/Handling Errors/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2368956098","text":"def solution(a):\n for i in a:\n largest=i[0]\n for j in i:\n if j>largest:\n largest=j\n yield largest\n\ndef main():\n a = [[11, 2, 3], [1, 2, 3, 4], [1, 2, 3]]\n for i in solution(a):\n print(i) \n\nmain()","repo_name":"Strangedip/PREP","sub_path":"Python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12918821363","text":"# %% [markdown]\n\"\"\"\n# 5. Asynchronous groups and services (basic)\n\nThe following tutorial shows `pipeline` asynchronous\nservice and service group usage.\n\nHere, %mddoclink(api,pipeline.service.group,ServiceGroup)s\nare shown for advanced and asynchronous data pre- and postprocessing.\n\"\"\"\n\n# %pip install dff\n\n# %%\nimport asyncio\n\nfrom dff.pipeline import Pipeline, ACTOR\n\nfrom dff.utils.testing.common import (\n is_interactive_mode,\n check_happy_path,\n run_interactive_mode,\n)\nfrom dff.utils.testing.toy_script import HAPPY_PATH, TOY_SCRIPT\n\n# %% [markdown]\n\"\"\"\nServices and service groups can be synchronous and asynchronous.\nIn synchronous service groups services are executed consequently.\nIn asynchronous service groups all services are executed simultaneously.\n\nService can be asynchronous if its handler is an async function.\nService group can be asynchronous if all services\nand service groups inside it are asynchronous.\n\nHere there is an asynchronous service group, that contains 10 services,\neach of them should sleep for 0.01 of a second.\nHowever, as the group is asynchronous,\nit is being executed for 0.01 of a second in total.\nService group `pipeline` can't be asynchronous because `actor` is synchronous.\n\"\"\"\n\n\n# %%\nasync def time_consuming_service(_):\n await asyncio.sleep(0.01)\n\n\npipeline_dict = {\n \"script\": TOY_SCRIPT,\n \"start_label\": (\"greeting_flow\", \"start_node\"),\n \"fallback_label\": (\"greeting_flow\", \"fallback_node\"),\n \"components\": [\n [time_consuming_service for _ in range(0, 10)],\n ACTOR,\n ],\n}\n\n# %%\npipeline = Pipeline.from_dict(pipeline_dict)\n\nif __name__ == \"__main__\":\n check_happy_path(pipeline, HAPPY_PATH)\n if is_interactive_mode():\n run_interactive_mode(pipeline)\n","repo_name":"deeppavlov/dialog_flow_framework","sub_path":"tutorials/pipeline/5_asynchronous_groups_and_services_basic.py","file_name":"5_asynchronous_groups_and_services_basic.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"85"} +{"seq_id":"38634139984","text":"import numpy as np\nimport ase\nfrom ase import Atoms\nfrom ase.cluster.cubic import FaceCenteredCubic\n\ndef wulff_construction(energies, wanted_atoms, lower_number = True, lattice_constant = 3.9160, element = 'Pt', fac_step = 0.05, print_result = True):\n \"\"\"\n energies: energies of crystal facets\n wanted_atoms: number of atoms wanted in the constructed Wulff shape.\n lower_number: if True, takes returns the structure with the largest\n amount of atoms below wanted_atoms. If false, returns the smallest above\n wanted_atoms.\n lattice_constant: lattice constant of the bulk FCC crystal.\n Element: chemical element.\n print_result: print the resulting number of atoms and respective layers.\n \"\"\"\n \n # The surfaces of this Wulff construction:\n surfaces = ((1,0,0),(1,1,0),(1,1,1),(-1,-1,-1))\n \n # Computing lengths of lattice directions based on lattice constant:\n l_100 = np.sqrt(1) * lattice_constant / 2\n l_110 = np.sqrt(2) * lattice_constant / 4\n l_111 = np.sqrt(3) * lattice_constant / 3\n L = np.array([l_100, l_110, l_111, l_111])\n\n EL = energies / L\n \n fac = 0\n n_atoms = 0\n while n_atoms < wanted_atoms:\n fac += fac_step\n layers = (EL * fac).astype(int)\n atoms = FaceCenteredCubic(element, surfaces, layers)\n n_atoms = len(atoms)\n\n if lower_number:\n # Taking the configuration smaller than the wanted number of atoms:\n fac -= fac_step\n layers = (EL * fac).astype(int)\n atoms = FaceCenteredCubic(element, surfaces, layers)\n \n if print_result:\n print('Resulting number of atoms:', len(atoms))\n print('Resulting number of layers:', layers)\n \n # Rotating the atoms object such that (-1,-1,-1) faces -z\n atoms.rotate((1,1,1), (0,0,np.sqrt(3))) \n \n return atoms\n","repo_name":"Matminator/thesis","sub_path":"Auxiliary_code/wulff_construction.py","file_name":"wulff_construction.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26862156606","text":"from head_hunter import get_vacancies_from_hh, extract_vacancies_from_hh\nfrom superjob import get_vacancies_from_sj, extract_vacancies_from_sj\nfrom terminaltables import SingleTable\n\nPROGRAMMING_LANGUAGES = [\n 'JavaScript',\n 'Java',\n 'Python',\n 'Ruby',\n 'PHP',\n 'C++',\n 'C#',\n 'C',\n 'Go',\n 'Objective-C',\n 'Scala',\n 'Swift',\n 'Typescript'\n]\n\n\ndef predict_rub_salary(pay_from, pay_to):\n if pay_from and pay_to:\n return (pay_from + pay_to) / 2\n elif pay_from:\n return pay_from * 1.2\n elif pay_to:\n return pay_to * 0.8\n\n\ndef get_statistic(vacancies):\n result = {}\n result['vacancies_found'] = vacancies['total']\n result['vacancies_processed'] = 0\n result['average_salary'] = 0\n for vacancy in vacancies['objects']:\n if vacancy['currency'] and \\\n vacancy['currency'] in ['RUR', 'rub']:\n salary = predict_rub_salary(vacancy['from'], vacancy['to'])\n if salary:\n result['average_salary'] += salary\n result['vacancies_processed'] += 1\n try:\n result['average_salary'] = \\\n int(result['average_salary']/result['vacancies_processed'])\n except ZeroDivisionError:\n result['average_salary'] = 0\n return result\n\n\ndef print_vacancy_info(title, vacancies):\n table_data = [\n [\n 'Язык программирования',\n 'Вакансий найдено',\n 'Вакансий обработано',\n 'Средняя зарплата'\n ]\n ]\n for language in vacancies:\n table_data.append([\n language,\n vacancies[language]['vacancies_found'],\n vacancies[language]['vacancies_processed'],\n vacancies[language]['average_salary']\n ])\n table_instance = SingleTable(table_data, title)\n print(table_instance.table)\n print()\n\nif __name__ == '__main__':\n result_from_hh = {}\n result_from_sj = {}\n for language in PROGRAMMING_LANGUAGES:\n vacancies_from_hh = get_vacancies_from_hh(language)\n vacancies_from_hh = extract_vacancies_from_hh(vacancies_from_hh)\n vacancies_from_sj = get_vacancies_from_sj(language)\n vacancies_from_sj = extract_vacancies_from_sj(vacancies_from_sj)\n result_from_hh[language] = get_statistic(vacancies_from_hh)\n result_from_sj[language] = get_statistic(vacancies_from_sj)\n\n print_vacancy_info('HeadHunter Moscow', result_from_hh)\n print_vacancy_info('SuperJob Moscow', result_from_sj)\n","repo_name":"keinen87/language-salary","sub_path":"language-salary/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41575520486","text":"from bs4 import BeautifulSoup\nimport requests # import the requests library module\nimport time\n\n# ask user to enter an unfamiliar skill\nunfamiliar_skill = input('Enter unfamiliar skill: ')\nprint(f'Filtering out {unfamiliar_skill}...')\n\n# Define the scraping function\ndef find_jobs():\n # get the html text of the webpage and store it in a variable called 'html_text'\n html_text = requests.get('https://www.timesjobs.com/candidate/job-search.html?searchType=Industry&from=submit&clubJob=n&cboIndustry=27&gadLink=IT-Hardware/Networking').text\n soup = BeautifulSoup(html_text, \"html.parser\")\n jobs = soup.find_all('li', class_='clearfix job-bx wht-shd-bx') # Get 1st job listings= by
  • tag\n for index, job in enumerate(jobs): # iterate through list of jobs\n publish_date = job.find('span', class_='sim-posted').span.text # get publish date\n if 'today' in publish_date: # only prints jobs posted today\n company_name = job.find('h3', class_='joblist-comp-name').text.replace(' ', '') # get company name, remove white spaces\n skills = job.find('span', class_='srp-skills').text.replace(' ', '') # get skills, remove white spaces\n link = job.header.h2.a['href'] # get link to job\n if unfamiliar_skill not in skills: # filter out unfamiliar skill\n # Write job info to text file\n with open(f'posts/{index}.txt', 'w') as f:\n f.write(f'Company name: {company_name.strip()} \\n')\n f.write(f'Required skills: {skills.strip()} \\n')\n f.write(f'More info: {link}')\n print(f'File saved: /posts/{index}.txt')\n\n\n\nif __name__ == '__main__':\n while True:\n find_jobs()\n time_wait = 10\n print(f'Waiting {time_wait} minutes...')\n time.sleep(time_wait * 60) # set program to run every 10 minutes\n","repo_name":"rachaelcole/Python_Projects","sub_path":"Web_Scraping/webscraper_5_requests.py","file_name":"webscraper_5_requests.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22264015960","text":"from typing import Any, Dict\n\nimport numpy as np\nimport torchvision.transforms as pth_transforms\nfrom classy_vision.dataset.transforms import register_transform\nfrom classy_vision.dataset.transforms.classy_transform import ClassyTransform\n\n\n@register_transform(\"ImgPilToMultiCrop\")\nclass ImgPilToMultiCrop(ClassyTransform):\n \"\"\"\n Convert a PIL image to Multi-resolution Crops.\n The input is a PIL image and output is the list of image crops.\n\n This transform was proposed in SwAV - https://arxiv.org/abs/2006.09882\n \"\"\"\n\n def __init__(self, total_num_crops, num_crops, size_crops, crop_scales):\n \"\"\"\n Returns total_num_crops square crops of an image. Each crop is a random crop\n extracted according to the parameters specified in size_crops and crop_scales.\n For ease of use, one can specify `num_crops` which removes the need to repeat\n parameters.\n\n Args:\n total_num_crops (int): Total number of crops to extract\n num_crops (List or Tuple of ints): Specifies the number of `type' of crops.\n size_crops (List or Tuple of ints): Specifies the height (height = width)\n of each patch\n crop_scales (List or Tuple containing [float, float]): Scale of the crop\n\n Example usage:\n - (total_num_crops=2, num_crops=[1, 1],\n size_crops=[224, 96], crop_scales=[(0.14, 1.), (0.05, 0.14)])\n Extracts 2 crops total of size 224x224 and 96x96\n - (total_num_crops=2, num_crops=[1, 2],\n size_crops=[224, 96], crop_scales=[(0.14, 1.), (0.05, 0.14)])\n Extracts 3 crops total: 1 of size 224x224 and 2 of size 96x96\n \"\"\"\n\n assert np.sum(num_crops) == total_num_crops\n assert len(size_crops) == len(num_crops)\n assert len(size_crops) == len(crop_scales)\n\n trans = []\n for i, sc in enumerate(size_crops):\n trans.extend(\n [\n pth_transforms.Compose(\n [pth_transforms.RandomResizedCrop(sc, scale=crop_scales[i])]\n )\n ]\n * num_crops[i]\n )\n\n self.transforms = trans\n\n def __call__(self, image):\n return list(map(lambda trans: trans(image), self.transforms))\n\n @classmethod\n def from_config(cls, config: Dict[str, Any]) -> \"ImgPilToMultiCrop\":\n \"\"\"\n Instantiates ImgPilToMultiCrop from configuration.\n\n Args:\n config (Dict): arguments for for the transform\n\n Returns:\n ImgPilToMultiCrop instance.\n \"\"\"\n return cls(**config)\n","repo_name":"yandex-research/DeDLOC","sub_path":"swav/vissl/vissl/data/ssl_transforms/img_pil_to_multicrop.py","file_name":"img_pil_to_multicrop.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"85"} +{"seq_id":"17203700938","text":"from flask import Flask, render_template, Response, request, jsonify\nimport logging\nimport logging.handlers\nfrom socket import timeout\nimport json\nfrom datetime import datetime, timedelta\nimport random\nimport time\nfrom apscheduler.scheduler import Scheduler\nimport sports\nimport entertainment\nimport platform\nimport os\nimport re\nimport urllib\nfrom urllib.request import Request, urlopen\nimport urllib.error\nfrom urllib.parse import quote\nfrom xml.etree import ElementTree as ET\nimport os.path\nimport news\nfrom operator import itemgetter\nimport requests\n\nweather_test = True\non_pi = False\nlocation = 84123\nicon = \"\"\nday = True\n\nday_night = 'day'\nday_night_old = ''\nfull_weather = []\ncurrent_rain = ''\nyield_me = ''\nforecast_high = []\nforecast_cond = []\n\n\n####### --== Set Platform ==-- #######\nprint(\"** Running on \" + platform.uname()[0] + \" **\")\nif platform.uname()[0] != 'Windows':\n on_pi = True\n\nif on_pi:\n import psutil\n import pexpect\n weather_test = False\n\n\napp = Flask(__name__)\n\nlogging.basicConfig(filename='errors.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n\nsched = Scheduler()\nsched.start()\n\n\n####### --== Write Streaming Stuff ==-- #######\ndef write_yield(event, data):\n global yield_me\n if type(data) is list:\n data = json.dumps(data)\n\n yield_me += 'event: ' + event + '\\n' + 'data: ' + str(data) + '\\n\\n'\n\n\n####### --== RSS Stuff ==-- #######\ndef get_rss():\n write_yield('rssFeed', news.get_news())\n\nget_rss()\nrss = sched.add_interval_job(get_rss, seconds=60 * 60)\n\n\n####### --== Weather Stuff ==-- #######\nweather_website = ('http://api.wunderground.com/api/c5e9d80d2269cb64/conditions/astronomy/forecast10day/alerts/' +\n 'hourly/q/%s.json' % location)\nallergy_website = 'http://www.claritin.com/weatherpollenservice/weatherpollenservice.svc/getforecast/84123'\n\n\ndef check_weather():\n global icon, day_night, current_rain, full_weather, forecast_cond, forecast_high\n if weather_test is False:\n global something_wrong\n global f, g\n try:\n f = urlopen(weather_website, timeout=3)\n req = Request(allergy_website, headers={'User-Agent': 'Mozilla/5.0'})\n g = urlopen(req, timeout=3)\n something_wrong = False\n except urllib.error.URLError as e:\n logging.error('Data not retrieved because - %s' % e)\n something_wrong = True\n except timeout:\n logging.error('Socket timed out')\n something_wrong = True\n\n if something_wrong:\n logging.error(\"No Internet\")\n else:\n hourly_temps = []\n forecast_cond = []\n forecast_day = []\n forecast_high = []\n forecast_low = []\n forecast_decription = []\n\n json_string = f.read()\n f.close()\n parsed_json = json.loads(json_string.decode(\"utf8\"))\n icon = parsed_json['current_observation']['icon']\n city_name = parsed_json['current_observation']['display_location']['full']\n observation_time = parsed_json['current_observation']['observation_time']\n current_cond = parsed_json['current_observation']['weather']\n relative_humidity = parsed_json['current_observation']['relative_humidity']\n precip_today_string = parsed_json['current_observation']['precip_today_string']\n wind_string = parsed_json['current_observation']['wind_string']\n current_rain = parsed_json['current_observation']['precip_today_in']\n\n sunset_hour = int(parsed_json['sun_phase']['sunset']['hour'])\n sunset_minute = int(parsed_json['sun_phase']['sunset']['minute'])\n sunrise_hour = int(parsed_json['sun_phase']['sunrise']['hour'])\n sunrise_minute = int(parsed_json['sun_phase']['sunrise']['minute'])\n day_or_night(sunset_hour, sunset_minute)\n write_yield('dayNight', day_night)\n\n for i in range(0, 12):\n hourly_temps.append(parsed_json['hourly_forecast'][i]['temp']['english'])\n write_yield('hourlyTemps', hourly_temps)\n\n j = 0\n for i in range(0, 5):\n forecast_cond.append(parsed_json['forecast']['simpleforecast']['forecastday'][i]['icon'])\n forecast_day.append(parsed_json['forecast']['simpleforecast']['forecastday'][i]['date']['weekday'])\n forecast_high.append(parsed_json['forecast']['simpleforecast']['forecastday'][i]['high']['fahrenheit'])\n forecast_low.append(parsed_json['forecast']['simpleforecast']['forecastday'][i]['low']['fahrenheit'])\n forecast_decription.append(parsed_json['forecast']['txt_forecast']['forecastday'][i + j]['fcttext'])\n j += 1\n\n write_yield('forecastCond', forecast_cond)\n write_yield('forecastDay', forecast_day)\n write_yield('forecastHigh', forecast_high)\n write_yield('forecastLow', forecast_low)\n write_yield('forecastDecription', forecast_decription)\n\n write_yield('tomTemp', parsed_json['forecast']['simpleforecast']['forecastday'][1]['high']['fahrenheit'])\n\n icon_image(icon)\n\n if parsed_json.get('alerts'):\n alert_description = parsed_json['alerts'][0]['description']\n alert_message = parsed_json['alerts'][0]['message']\n write_yield('alert', [alert_description, alert_message])\n else:\n write_yield('alert', ['', ''])\n\n json_string = g.read()\n g.close()\n parsed_json = json.loads(json_string.decode('utf-8'))\n set1 = parsed_json.find(':[')\n set2 = parsed_json.find('],')\n set3 = parsed_json.find('\"pp')\n set4 = parsed_json.find('\"timestamp')\n write_yield('predominantPollen', parsed_json[set3 + 6: set4 - 3])\n allergy_forecast = parsed_json[set1 + 2: set2]\n write_yield('allergyForecast', str(allergy_forecast).split(\",\"))\n\n full_weather = [city_name, observation_time, current_cond, sunset_hour, sunset_minute, sunrise_hour,\n sunrise_minute, relative_humidity, precip_today_string, wind_string]\n write_yield('fullWeather', full_weather)\n\n else: # Random test weather\n def rand_weather():\n randt = ['rain', 'clear', 'partlycloudy', 'mostlycloudy', 'flurries', 'snow', 'sunny', 'sleet',\n 'partlysunny', 'mostlysunny', 'tstorms', 'cloudy', 'fog', 'hazy', 'chancetstorms', 'chancerain',\n 'chancesnow', 'unknown']\n return randt[random.randrange(0, 18)]\n\n def rand_days():\n randt = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']\n return randt[random.randrange(0, 5)]\n\n def get_rand():\n return random.randrange(60, 90)\n\n icon = rand_weather()\n write_yield('tomTemp', get_rand())\n write_yield('forecastDay', [rand_days(), rand_days(), rand_days(), rand_days(), rand_days()])\n forecast_cond = [rand_weather(), rand_weather(), rand_weather(), rand_weather(), rand_weather()]\n write_yield('forecastCond', forecast_cond)\n write_yield('forecastHigh', [get_rand(), get_rand(), get_rand(), get_rand(), get_rand()])\n write_yield('forecastLow', [get_rand(), get_rand(), get_rand(), get_rand(), get_rand()])\n write_yield('forecastDecription', forecast_cond)\n\n if day_night == 'day':\n day_night = 'night'\n else:\n day_night = 'day'\n\n write_yield('dayNight', day_night)\n\n def rand_allergy():\n return random.randrange(10, 120) / 10\n\n write_yield('allergyForecast', [rand_allergy(), rand_allergy(), rand_allergy(), rand_allergy()])\n write_yield('predominantPollen', rand_weather())\n city_name = \"Murray\"\n observation_time = datetime.now().strftime('%m/%d/%Y %I:%M:%S %p')\n current_cond = icon\n sunset_hour = 22\n sunset_minute = 23\n sunrise_hour = 7\n sunrise_minute = 12\n relative_humidity = '32%'\n precip_today_string = '0.00 in'\n wind_string = 'Wind out of the East at 7MPH'\n\n full_weather = [city_name, observation_time, current_cond, sunset_hour, sunset_minute, sunrise_hour,\n sunrise_minute, relative_humidity, precip_today_string, wind_string]\n write_yield('fullWeather', full_weather)\n write_yield('hourlyTemps', [get_rand(), get_rand(), get_rand(), get_rand(), get_rand(), get_rand(), get_rand(),\n get_rand(), get_rand(), get_rand(), get_rand(), get_rand()])\n\n icon_image(icon)\n write_yield('alert', ['', ''])\n\n\ndef icon_image(icon_name):\n global icon\n if icon_name == 'partlysunny':\n icon_name = 'mostlycloudy'\n elif icon_name == 'mostlysunny':\n icon_name = 'partlycloudy'\n elif icon_name == 'sunny':\n icon_name = 'clear'\n elif icon_name[0:6] == 'chance':\n icon_name = icon_name[6:]\n else:\n icon_name = icon_name\n\n rand = random.randint(1, 5)\n fname = 'static/images/bg/' + day_night + '-' + icon_name + '-' + str(rand) + '.jpg'\n\n if os.path.exists(fname):\n write_yield('icon', fname)\n else:\n icon_image(icon_name)\n\n\ndef day_or_night(sh, sm):\n global day_night\n sunset = datetime.now().replace(hour=int(sh), minute=int(sm),\n second=00, microsecond=0)\n\n if (sunset - datetime.now()).total_seconds() > 0:\n day_night = 'day'\n else:\n day_night = 'night'\n\ncheck_weather()\ndt = datetime.now()\nif on_pi:\n if dt.minute > 30:\n weather = sched.add_interval_job(check_weather, seconds=30 * 60, start_date=((dt + timedelta(hours=1)).replace(minute=0, second=0)))\n else:\n weather = sched.add_interval_job(check_weather, seconds=30 * 60, start_date=(dt.replace(minute=30, second=0)))\nelse:\n weather = sched.add_interval_job(check_weather, seconds=60)\n\n\n####### --== Get Temps ==-- #######\nif on_pi:\n os.system('modprobe w1-gpio')\n os.system('modprobe w1-therm')\n temperature_file = '/sys/bus/w1/devices/28-0004749a3dff/w1_slave'\n\n\ndef get_temps_from_probes():\n global in_temp\n if on_pi:\n y = open(temperature_file, 'r')\n lines = y.readlines()\n y.close()\n\n if lines[0].strip()[-3:] != 'YES':\n print('No temp from sensor.')\n else:\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos + 2:]\n temp_c = float(temp_string) / 1000.0\n in_temp = temp_c * 9.0 / 5.0 + 32.0\n write_yield('inTemp', in_temp)\n #print(in_temp)\n\n write_yield('outTemp', str(random.randrange(-32, 104)))\n\n else:\n write_yield('outTemp', str(random.randrange(-32, 104)))\n write_yield('inTemp', str(random.randrange(32, 104)))\n\nget_temps_from_probes()\ntemps = sched.add_interval_job(get_temps_from_probes, seconds=15)\n\n\n####### --== Music Stuff ==-- #######\nartist = ''\nalbum = ''\nsong = ''\ninformation = ['', '', '']\ninfo_old = []\nst = None\nh = None\np = None\nplaying = False\nst_got = False\n\n\ndef get_album(song2, artist2, album2, like2):\n try:\n global album_info\n last_fm_website = 'http://ws.audioscrobbler.com/2.0/?method=album.getinfo&' \\\n 'api_key=7e0ead667c3b37eb1ed9f3d16778fe38&artist=%s&album=%s&format=json' \\\n % (quote(artist2), quote(album2))\n chartlyrics_website = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?' \\\n 'artist=%s&song=%s' % (quote(artist2), quote(song2))\n\n q = urlopen(last_fm_website)\n json_string = q.read()\n parsed_json = json.loads(json_string.decode('utf-8'))\n if 'image' in parsed_json['album']:\n album_art = parsed_json['album']['image'][3]['#text']\n else:\n album_art = '/static/images/pandora/blank.jpg'\n if 'wiki' in parsed_json['album']:\n album_sum = re.sub('<[^<]+?>', '', parsed_json['album']['wiki']['summary'])\n else:\n album_sum = ''\n\n try:\n print('Getting lyrics')\n t = ET.parse(urlopen(chartlyrics_website))\n items = t.getroot()\n lyrics = items[9].text.replace('\\n', '
    ')\n if lyrics is None:\n lyrics = ''\n except:\n lyrics = ''\n\n album_info = [song2, artist2, album2, album_art, album_sum, like2, lyrics]\n write_yield('albumInfo', album_info)\n print(album_info)\n except:\n album_info = [song2, artist2, album2, '/static/images/pandora/blank.jpg', '', like2, '']\n print(album_info)\n write_yield('albumInfo', album_info)\n\n\ndef start_pianobar():\n global pianobar, h, playing, artist, album, song, information, info_old\n pianobar = pexpect.spawnu('sudo -u pi pianobar')\n\n playing = True\n #pattern_list = pianobar.compile_pattern_list(['SONG: ', 'STATION: ', 'TIME: '])\n print('Getting info')\n\n while pianobar.isalive():\n while playing:\n try:\n x = pianobar.expect('SONG: ', timeout=0)\n if x == 0:\n song = ''\n artist = ''\n album = ''\n like = ''\n\n x = pianobar.expect(' \\| ')\n if x == 0: # Title | Artist | Album\n print('Song: \"%s\"' % pianobar.before)\n song = pianobar.before\n x = pianobar.expect(' \\| ')\n if x == 0:\n print('Artist: \"{}\"'.format(pianobar.before))\n artist = pianobar.before\n x = pianobar.expect(' \\| ')\n if x == 0:\n print('Album: \"{}\"'.format(pianobar.before))\n album = pianobar.before\n if re.search('\\(', album) is not None:\n album = album[:re.search('\\(', album).start()]\n x = pianobar.expect('\\r\\n')\n if x == 0:\n print('Like: \"{}\"'.format(pianobar.before))\n if pianobar.before == '<3':\n like = '1'\n else:\n like = '0'\n\n info_old = information\n information = [song, artist, album, like]\n if information != info_old:\n get_album(song, artist, album, like)\n\n # elif x == 1:\n # x = pianobar.expect(' \\| ')\n # if x == 0:\n # print('Station: \"{}\"'.format(pianobar.before))\n # elif x == 2:\n # # Time doesn't include newline - prints over itself.\n # x = pianobar.expect('\\r', timeout=1)\n # if x == 0:\n # print('Time: {}'.format(pianobar.before))\n\n except pexpect.EOF:\n break\n except pexpect.TIMEOUT:\n break\n\n\ndef get_stations():\n global h, stations, st, st_got\n print('Getting stations')\n pianobar.sendcontrol('m')\n try:\n pianobar.expect('TIME: ', timeout=30)\n pianobar.sendline('s')\n try:\n pianobar.expect('Select station: ', timeout=30)\n a = pianobar.before.splitlines()\n stations = []\n\n for b in a[:-1]:\n if (b.find('playlist...') >= 0) or (b.find('Autostart') >= 0) or (b.find('TIME:') >= 0):\n continue\n if b.find('Radio') or b.find('QuickMix'):\n id_no = b[5:7].strip()\n name = b[13:].strip()\n\n if name == 'QuickMix':\n stations.insert(0, [id_no, name])\n else:\n stations.append([id_no, name])\n pianobar.sendcontrol('m')\n st_got = True\n print(str(stations).replace('],', ']\\n'))\n write_yield('stations', stations)\n\n except pexpect.TIMEOUT:\n get_stations()\n except pexpect.TIMEOUT:\n get_stations()\n\n\ndef change_station_by_id(id_no):\n global pianobar\n print(\"Change to station #\" + id_no)\n print('Clear out of any selection.')\n pianobar.sendcontrol('m')\n print('Press s')\n pianobar.send('s')\n print('Wait for \"Select station:\"')\n try:\n pianobar.expect('Select station: ', timeout=30)\n print('Press ' + id_no)\n pianobar.send(id_no)\n print('Press enter')\n pianobar.sendcontrol('m')\n print('Changed')\n except pexpect.TIMEOUT:\n print('Timed out - try again')\n change_station_by_id(id_no)\n\n\n####### --== Entertainment Stuff ==-- #######\ndef get_opening_movies():\n write_yield('openingMovies', entertainment.get_opening_movies())\n\n\ndef get_local_events():\n write_yield('localEvents', entertainment.get_local_events())\n\nget_opening_movies()\ndt = datetime.now()\nmovies = sched.add_interval_job(get_opening_movies, days=7, start_date=(dt + timedelta(days=7) - timedelta(days=dt.weekday() - 1)).replace(hour=0, minute=2, second=0))\nget_local_events()\nevents = sched.add_interval_job(get_local_events, days=1, start_date=(dt + timedelta(days=1)).replace(hour=0, minute=2, second=0))\n\n\ndef get_jeopardy():\n write_yield('jeopardy', entertainment.jeopardy())\n\n# get_jeopardy()\njeopardy = sched.add_interval_job(get_jeopardy, seconds=60 * 60, start_date=(dt + timedelta(hours=1)).replace(minute=10, second=0))\n\n\ndef get_cheezburger():\n get = entertainment.cheezburger()\n if get != '':\n write_yield('cheezburger', get)\n\n# get_cheezburger()\ncheezburger = sched.add_interval_job(get_cheezburger, seconds=random.randint(45, 90) * 60, start_date=(dt + timedelta(hours=1)).replace(minute=15, second=0))\n\n\ndef get_flickr():\n write_yield('flickr', entertainment.flickr())\n\nget_flickr()\nflickr = sched.add_interval_job(get_flickr, seconds=random.randint(45, 90) * 60, start_date=(dt + timedelta(hours=1)).replace(minute=45, second=0))\n\n\ndef get_facts():\n get = entertainment.sotruefacts()\n if get != '':\n write_yield('facts', get)\n\n# get_facts()\nfacts = sched.add_interval_job(get_facts, seconds=random.randint(45, 90) * 60, start_date=(dt + timedelta(hours=1)).replace(minute=55, second=0))\n\n####### --==Holiday Stuff==-- #######\nholidays = [\"New Year\\u2019s Day\", \"Groundhog Day\", \"Valentine\\u2019s Day\", \"Washington\\u2019s Birthday\",\n \"Saint Patrick\\u2019s Day\", \"April Fools\\u2019 Day\", \"Earth Day\", \"Star Wars Day\", \"Cinco de Mayo\",\n \"Mother\\u2019s Day\", \"Memorial Day\", \"Flag Day\", \"Father\\u2019s Day\", \"Independence Day\", \"Labor Day\",\n \"Halloween\", \"Veterans Day\", \"Thanksgiving Day\", \"Christmas\", \"New Year\\u2019s Eve\", \"Easter\"]\nlike_holiday = [\"Saint Patrick\\u2019s Day\", \"Halloween\", \"Thanksgiving Day\", \"Christmas\"]\nholiday_list = []\n\n\ndef get_holidays():\n global holiday_list\n holiday_website = 'http://holidayapi.com/v1/holidays?country=US&year=%s' % datetime.now().year\n w = urlopen(holiday_website)\n json_string = w.read()\n parsed_json = json.loads(json_string.decode('utf-8'))\n for i in parsed_json['holidays']:\n for j in parsed_json['holidays'][i]:\n if j['name'] in holidays:\n holiday_list.append([j['date'], j['name']])\n\n holiday_list = sorted(holiday_list, key=itemgetter(0))\n\n\nget_holidays()\nholiday_sched = sched.add_interval_job(get_holidays, days=365, start_date=datetime.now()\n .replace(year=datetime.now().year + 1, month=1, day=1, hour=0, minute=5))\n\n\ndef check_holiday():\n for i in holiday_list:\n da = datetime.strptime(i[0], '%Y-%m-%d')\n if (da - datetime.now()).total_seconds() > 0:\n if i[1] in like_holiday:\n if (da - datetime.now()).days < 14:\n write_yield('holiday', i)\n else:\n holiday_day = sched.add_date_job(run_holiday, da - timedelta(days=-14).replace(hour=0, minute=1, second=0), args=i)\n break\n else:\n if (da - datetime.now()).days < 3:\n write_yield('holiday', i)\n else:\n holiday_day = sched.add_date_job(run_holiday, (da - timedelta(days=-3)).replace(hour=0, minute=1, second=0), args=i)\n break\n else:\n pass\n\n\ndef run_holiday(hday):\n write_yield('holiday', hday)\n\n\ncheck_holiday()\nholiday_day_sched = sched.add_interval_job(check_holiday, days=1, start_date=(datetime.now() + timedelta(days=1)).replace(hour=0, minute=2))\n\n\n#sched.print_jobs()\nprint('OK GO')\ntemp_yield = yield_me\n\n####### --==Web Part==-- #######\ntry:\n @app.route('/my_event_source')\n def sse_request():\n global yield_me\n temp = yield_me\n yield_me = ''\n return Response(temp, mimetype='text/event-stream')\n\n @app.route('/')\n def my_form():\n global yield_me\n yield_me = temp_yield\n return render_template(\"index.html\")\n\n @app.route('/entertainment', methods=['POST'])\n def send_to_phone():\n a = request.form.get('a', 'something is wrong', type=str)\n b = request.form.get('b', 'something is wrong', type=str)\n print(a + ' - ' + b)\n if on_pi:\n data = dict(title=a, url=b, type='link')\n api_key = 'v1DxHg2oyCZCPc5Xr6KiVh4X3sLfkdibX2ujBvxC0RbUW'\n requests.post('https://api.pushbullet.com/v2/pushes', auth=(api_key, ''), data=data)\n return jsonify({'1': ''})\n\n @app.route('/music', methods=['POST'])\n def music_control():\n global pianobar, h, st\n button = request.form.get('button', 'something is wrong', type=str)\n print(button + ' button pressed')\n if on_pi:\n if button == 'P':\n for proc in psutil.process_iter():\n if 'pianobar' in proc.name():\n print('pianobar running')\n pianobar.send(button)\n break\n else:\n print('starting pianobar')\n h = sched.add_date_job(start_pianobar, (datetime.now() + timedelta(seconds=2)))\n st = sched.add_date_job(get_stations, (datetime.now() + timedelta(seconds=20)))\n else:\n pianobar.send(button)\n else:\n pianobar.send(button)\n return jsonify({'1': ''})\n\n @app.route('/stationSelect', methods=['POST'])\n def change_station():\n global h\n id_no = request.form.get('id', 'something is wrong', type=str)\n h = sched.add_date_job(change_station_by_id, (datetime.now() + timedelta(seconds=2)), args=id_no)\n return jsonify({'1': ''})\n\n @app.route('/weather.json', methods=['GET'])\n def give_weather():\n return jsonify({'weather': full_weather[2], 'ssHour': full_weather[3], 'ssMinute': full_weather[4],\n 'rain': current_rain, 'forecast_temp': forecast_high, 'forecast_cond': forecast_cond})\n\n if __name__ == '__main__':\n app.run(host='0.0.0.0', port=88)\n\nfinally:\n print('Shutting Down!')\n playing = False\n print('Killing pianobar')\n try:\n pianobar.sendline('q')\n except:\n pass\n for procs in psutil.process_iter():\n if 'pianobar' in procs.name():\n print('Didn\\'t kill, killing harder - pid ' + str(procs.pid))\n os.system('sudo kill ' + str(procs.pid))\n print('Shutting down scheduler')\n sched.shutdown(wait=False)\n print('Clear errors log')\n f = open('errors.log', 'w')\n f.close()\n print('Done')","repo_name":"punksux/Infotainment","sub_path":"info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":24202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"6745456904","text":"#!/usr/bin/python\n\nimport json\n\n\ncountryFile = \"../data/reducedGeography.json\"\noutputFile = \"../data/reducedGeography.json\"\n\nprint(\"Opening file..\")\ndataFile = open(countryFile)\ndataJSON = json.load(dataFile)[\"features\"]\n\nprint(\"Processing file..\")\nfor f in dataJSON:\n geomList = f[\"geometry\"][\"coordinates\"]\n multiPoly = f[\"geometry\"][\"type\"] == \"MultiPolygon\"\n for geom in geomList:\n if (multiPoly):\n geom = geom[0]\n cutPoints = []\n for i in range(0, len(geom)):\n if (geom[i][0] > 180):\n print(\"editing \" + str(geom[i]))\n geom[i][0] = 180\n elif (geom[i][0] < -180):\n print(\"editing \" + str(geom[i]))\n geom[i][0] = -180\n\n\n\ndataFile.close()\n\noutputJSON = {}\noutputJSON[\"type\"] = \"FeatureCollection\"\noutputJSON[\"features\"] = dataJSON\n\nprint(\"Writing output to file..\")\njsonWrite = open(outputFile, \"w+\")\njsonWrite.write(json.dumps(outputJSON, separators = (',', ':')))\njsonWrite.close()\n\nprint(\"Done.\")","repo_name":"justsz/pandemix","sub_path":"python/antimeridianFix.py","file_name":"antimeridianFix.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16012294461","text":"import threading\nimport time\n\n\nticket = 30\n\n# 线程锁效率降低\n\n# 创建一把锁\nlock = threading.Lock()\n\ndef sell_tic():\n # ticket -= 1\n # if ticket <= 0:\n # print('Piaomaiwanle')\n\n # 多个线程共享全局变量\n # 线程安全问题\n # 多线程是切换的 不是同时 因为时间很短所以显示为同时\n global ticket\n while True:\n lock.acquire() # 加同步锁\n if ticket > 0:\n time.sleep(0.5) # 单线程卖票\n ticket -= 1\n lock.release() # 加线程锁\n print('{}卖出一张还剩{}张\\n'.format(threading.current_thread().name,ticket))\n else:\n lock.release() # 加线程锁\n print('meipiaole')\n\n break\n\n\n# sell_tic()\nt1 = threading.Thread(target=sell_tic,name='线程1') # 线程1\nt2 = threading.Thread(target=sell_tic,name='线程2') # 线程2\n# 多个窗口一起卖\n\nt2.start()\nt1.start()\n\n","repo_name":"Rookie1019/data_share","sub_path":"Python总文件夹/python4-30/53-多线程开发(卖票线程锁).py","file_name":"53-多线程开发(卖票线程锁).py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28858499845","text":"import json\nimport requests\n\n\ndef get_gitlab_version(address: str, token: str) -> str:\n \"\"\"\n Gets the version of a gitlab instance\n :param address: The address of the gitlab instance (excluding https)\n :param token: The API token used for authentication\n :return: The version, minus any\n \"\"\"\n resp = json.loads(requests.get(\n \"https://{}/api/v4/version\".format(address),\n headers={\n \"PRIVATE-TOKEN\": token\n }\n ).text)\n print(resp)\n print(token)\n return resp[\"version\"].split(\"-\")[0].strip()\n\n\ndef get_version_from_version_file(version_file: str) -> str:\n \"\"\"\n Retrieves the version based on a version file\n :param version_file: The version file to read\n :return: The version\n \"\"\"\n return requests.get(version_file).text.strip()\n","repo_name":"namboy94/status-page","sub_path":"status_page/analytics/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"40633641116","text":"\n\nfrom xml.etree import ElementTree as ET\n\ndef create_data_properties_from_csx(xml_path):\n doc = ET.parse(xml_path)\n elements = doc.findall(\".//Element\")\n\n for element in elements:\n offset = int(element.attrib['Offset'])\n bytesize = int(element.attrib['Bytesize'])\n name = element.attrib.get(\"Description\", None)\n if bytesize == 4:\n fmt = \"I\"\n elif bytesize == 2:\n fmt = \"H\"\n elif bytesize == 1:\n fmt = \"B\"\n else:\n raise Exception(f\"no format for bytesize: {bytesize}\")\n\n yield name, fmt, offset\n\n\n\n\n\n","repo_name":"sourcehold/sourcehold-maps","sub_path":"sourcehold/debugtools/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"85"} +{"seq_id":"12405693197","text":"from __future__ import absolute_import, unicode_literals\nimport os\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'JRstock.settings')\nimport django\ndjango.setup()\nfrom firebase_admin import messaging\n\ndef send_to_fcm(token, result_id):\n message = messaging.Message(\n data={\n \"title\":\"백테스트 완료\",\n \"contents\": \"요청하신 백테스팅이 완료되었습니다\",\n \"url\": \"https://j6s001.p.ssafy.io/backtest/\" + str(result_id)\n },\n token=token,\n )\n messaging.send(message)","repo_name":"Hasky96/JRStock","sub_path":"backend/backtest/fcm.py","file_name":"fcm.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"70396216278","text":"import os\r\nPATH = os.path.dirname(os.path.realpath(__file__))\r\nFILENAME = \"out.txt\"\r\n\r\ndef add_student():\r\n studentid = input(\"Please enter student ID: \")\r\n firstname = input(\"Please enter first name: \")\r\n lastname = input(\"Please enter last name: \")\r\n major = input(\"Please enter major: \")\r\n phone = input(\"Please enter phone: \")\r\n gpa = input(\"Please enter gpa: \")\r\n birth = input(\"Please enter date of birth: \")\r\n student = [studentid + \" \", firstname + \" \", lastname + \" \", major + \" \", phone + \" \", gpa + \" \", birth]\r\n with open(FILENAME, \"a\") as file:\r\n for n in student:\r\n file.write(n)\r\n file.write(\"\\n\")\r\n\r\ndef read_student():\r\n id = input(\"Please enter the ID of the student you are looking for: \")\r\n student = []\r\n with open(FILENAME, \"r\") as file:\r\n for line in file:\r\n line = line.replace(\"\\n\", \"\")\r\n student.append(line)\r\n matching = [s for s in student if id in s]\r\n print(matching)\r\n\r\ndef action():\r\n print(\"Welcome to Student Manager 1.0\")\r\n print(\"------------------------------\")\r\n print(\"Use Add command to add student.\")\r\n print(\"Use Read command to read student information.\")\r\n print(\"Use Exit command to exit.\")\r\n print(\"------------------------------\")\r\n\r\ndef main():\r\n action()\r\n while True:\r\n command = input(\"Please enter a command: \")\r\n if command.lower() == \"add\":\r\n add_student()\r\n elif command.lower() == \"read\":\r\n read_student()\r\n elif command.lower() == \"exit\":\r\n break\r\n else:\r\n print(\"Invalid command\")\r\n print(\"------------------------------\")\r\n print(\"Bye!\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"dustinle48/COMP2152_PythonProject","sub_path":"labtest2.py","file_name":"labtest2.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38434383275","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef main():\n num = 0\n accm = 0.0\n for line in sys.stdin:\n try:\n value = int(line.strip())\n except ValueError:\n continue\n\n num += 1\n accm += value\n print(\"{0:f}\".format(accm/num))\n\nif __name__ == '__main__':\n main()\n","repo_name":"0ncorhynchus/macs","sub_path":"ave_trans.py","file_name":"ave_trans.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"38286126611","text":"\"\"\"\nGiven a number N and array of N integers, print the prefix sum array for each position if it is divisible by 2 else print the element itself.\nInput Size : N <= 10000\nSample Testcase :\nINPUT\n4\n2 4 4 4\nOUTPUT\n2 6 10 14\n\"\"\"\nn=int(input())\na=map(int,input().split()[:n])\na=list(a)\nc=a[0]\nl=[]\nl.append(a[0])\nfor i in range(1,n):\n c=c+a[i]\n if(c%2==0):\n l.append(c)\n else:\n l.append(a[i])\nl=\" \".join(map(str,l))\nprint(l)","repo_name":"Velu2498/codekata-array-python","sub_path":"157.py","file_name":"157.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"70706986838","text":"#!/usr/bin/env python3\n\n# this causes flash corruption [?] in the cw303 xmega target\n# power cycling does nothing, reprogram your target to keep playing.\n\nimport time\nimport logging\nimport os\nfrom collections import namedtuple\nimport csv\n\nimport numpy as np\n\nimport chipwhisperer as cw\nfrom chipwhisperer.capture.api.programmers import XMEGAProgrammer\nlogging.basicConfig(level=logging.WARN)\nscope= cw.scope()\ntarget = cw.target(scope)\n\nscope.glitch.clk_src = 'clkgen'\n\nscope.gain.gain = 25\nscope.adc.samples = 3000\nscope.adc.offset = 0\nscope.adc.basic_mode = \"rising_edge\"\nscope.clock.clkgen_freq = 7370000\nscope.clock.adc_src = \"clkgen_x4\"\nscope.trigger.triggers = \"tio4\"\nscope.io.tio1 = \"serial_rx\"\nscope.io.tio2 = \"serial_tx\"\n# scope.io.hs2 = \"glitch\"\nscope.io.hs2 = \"clkgen\"\nscope.glitch.output = \"glitch_only\"\nscope.io.glitch_lp = False\nscope.io.glitch_hp = True\nprint(scope.io.glitch_lp)\nprint(scope.io.glitch_hp)\ntarget.go_cmd = \"\"\ntarget.key_cmd = \"\"\n\nprint(\"Erase target...\")\n\n# program the XMEGA with the built hex file\nprogrammer = XMEGAProgrammer()\nprogrammer.scope = scope\nprogrammer._logging = None\nprogrammer.find()\nprogrammer.erase()\n\nprint(\"Programming...\")\n\n\nprogrammer.program(\"glitchsimple.hex\", memtype=\"flash\", verify=True)\nprogrammer.close()\n\nscope.glitch.trigger_src = 'ext_single'\n\ntraces = []\noutputs = []\nwidths = []\noffsets = []\n\nRange = namedtuple('Range', ['min', 'max', 'step'])\nrepeat_range = Range(1,5,2)\nwidth_range = Range(20.3,20.4,0.3)\noffset_range = Range(29.9,30.7,0.3)\nscope.glitch.ext_offset = 5\n\n# scope.glitch.offset = 27.7\n\nscope.glitch.offset = offset_range.min\n\n# pew pew pew\nscope.glitch.width = width_range.min\ntarget.init()\nwhile scope.glitch.width < width_range.max:\n while scope.glitch.offset < offset_range.max:\n scope.glitch.repeat = repeat_range.min\n while scope.glitch.repeat < repeat_range.max:\n output = \"\"\n target.ser.flush()\n\n scope.io.pdic = 'low'\n scope.io.pdic = 'high'\n\n scope.arm()\n timeout = 100\n while target.isDone() is False and timeout:\n timeout -= 1\n time.sleep(0.01)\n\n try:\n ret = scope.capture()\n if ret:\n logging.warning('Timeout happened during acquisition')\n except IOError as e:\n logging.error('IOError: %s' % str(e))\n\n trace = scope.get_last_trace()\n output = target.ser.read(64, timeout=500) #onl yneed first char\n print(\"R=%d:W=%f:O=%f:%s\" % (scope.glitch.repeat,scope.glitch.width,scope.glitch.offset,repr(output)))\n if \"1234\" in output:\n print(\"done\")\n scope.dis()\n target.dis()\n import sys\n sys.exit(0)\n # traces.append(trace)\n scope.glitch.repeat += repeat_range.step\n print(\"Adding e...\")\n scope.glitch.offset += offset_range.step\n print(\"Adding w...\")\n scope.glitch.width += width_range.step\n scope.glitch.offset = offset_range.min\nprint('Done')\n\nscope.dis()\ntarget.dis()\n","repo_name":"CreateRemoteThread/gofuckyourself","sub_path":"cwtest/cw-xmega303.py","file_name":"cw-xmega303.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"15699062893","text":"# -*- coding: utf-8 -*-\n\nfrom six.moves import range as xrange\nfrom thrift.Thrift import TType\n\n\nclass Error(Exception):\n pass\n\n\nclass ObjectTooBig(Error):\n pass\n\n\nclass ThriftStruct(object):\n \"\"\"A thrift struct\"\"\"\n\n def __init__(self, fields, length=0):\n self._fields = fields\n self._length = length # in bytes\n\n @property\n def bytes_length(self):\n return self._length\n\n @property\n def as_dict(self):\n return {\n 'fields': [field.as_dict for field in self.fields]\n }\n\n @property\n def fields(self):\n return self._fields\n\n def is_isomorphic_to(self, other):\n \"\"\"\n Returns true if all fields of other struct are isomorphic to this\n struct's fields\n \"\"\"\n return (isinstance(other, self.__class__)\n and\n len(self.fields) == len(other.fields)\n and\n all(a.is_isomorphic_to(b) for a, b in zip(self.fields,\n other.fields)))\n\n def __eq__(self, other):\n \"\"\" we ignore the length, it might not be set \"\"\"\n return isinstance(other, self.__class__) and self.fields == other.fields\n\n def __len__(self):\n \"\"\" number of fields, NOT number of bytes \"\"\"\n return len(self._fields)\n\n def __getitem__(self, key):\n return self._fields[key]\n\n def __iter__(self):\n return iter(self._fields)\n\n def __repr__(self):\n return \"fields=%s\" % self.fields\n\n @classmethod\n def read(cls,\n proto,\n max_fields,\n max_list_size,\n max_map_size,\n max_set_size,\n read_values=False):\n fields = []\n nfields = 0\n\n start = proto.trans._buffer.tell()\n\n proto.readStructBegin()\n while True:\n nfields += 1\n if nfields >= max_fields:\n raise ObjectTooBig('too many fields: %d' % nfields)\n\n _, ftype, fid = proto.readFieldBegin()\n if ftype == TType.STOP:\n break\n\n value = cls.read_field_value(\n proto, ftype,\n max_fields,\n max_list_size,\n max_map_size,\n max_set_size,\n read_values)\n\n proto.readFieldEnd()\n\n fields.append(ThriftField(cls.field_type_to_str(ftype), fid, value))\n proto.readStructEnd()\n\n end = proto.trans._buffer.tell()\n length = end - start\n\n return cls(fields, length)\n\n @classmethod\n def read_field_value(cls, proto, ftype,\n max_fields,\n max_list_size,\n max_map_size,\n max_set_size,\n read_values):\n value = None\n\n def _read(_type):\n return cls.read_field_value(\n proto,\n _type,\n max_fields,\n max_list_size,\n max_map_size,\n max_set_size,\n read_values)\n\n # ##\n # There's a lot going on here:\n #\n # * for known scalar types, we check if we want the value or we skip\n # * for known collections, ditto but with sane size/limit checks\n # * for the rest we skip\n #\n # Touching a line here should warrant writing another test case :-)\n #\n # FIXME: the way bytes are skipped is very lame, we should calculate\n # the total number of bytes that are to be skipped, and have\n # the transport seek() to that point.\n\n if ftype == TType.STRUCT:\n value = cls.read(\n proto,\n max_fields,\n max_list_size,\n max_map_size,\n max_set_size,\n read_values\n )\n elif ftype == TType.I32:\n if read_values:\n value = proto.readI32()\n else:\n proto.skip(ftype)\n elif ftype == TType.I64:\n if read_values:\n value = proto.readI64()\n else:\n proto.skip(ftype)\n elif ftype == TType.STRING:\n if read_values:\n try:\n value = proto.readString()\n except UnicodeDecodeError:\n value = ''\n else:\n proto.skip(ftype)\n elif ftype == TType.LIST:\n (etype, size) = proto.readListBegin()\n if size > max_list_size:\n raise ObjectTooBig('list too long: %d' % size)\n value = []\n if read_values:\n value = [_read(etype) for _ in xrange(size)]\n else:\n for _ in xrange(size):\n proto.skip(etype)\n proto.readListEnd()\n elif ftype == TType.MAP:\n (ktype, vtype, size) = proto.readMapBegin()\n if size > max_map_size:\n raise ObjectTooBig('map too big: %d' % size)\n value = {}\n if read_values:\n for _ in xrange(size):\n k = _read(ktype)\n v = _read(vtype)\n value[k] = v\n else:\n for _ in xrange(size):\n proto.skip(ktype)\n proto.skip(vtype)\n proto.readMapEnd()\n elif ftype == TType.SET:\n (etype, size) = proto.readSetBegin()\n if size > max_set_size:\n raise ObjectTooBig('set too big: %d' % size)\n value = set()\n if read_values:\n for _ in xrange(size):\n value.add(_read(etype))\n else:\n for _ in xrange(size):\n proto.skip(etype)\n proto.readSetEnd()\n else:\n # for now, we ignore all other values\n proto.skip(ftype)\n\n return value\n\n @staticmethod\n def field_type_to_str(ftype):\n if ftype == TType.STOP:\n return 'stop'\n elif ftype == TType.VOID:\n return 'void'\n elif ftype == TType.BOOL:\n return 'bool'\n elif ftype == TType.BYTE:\n return 'byte'\n elif ftype == TType.I08:\n return 'i08'\n elif ftype == TType.DOUBLE:\n return 'double'\n elif ftype == TType.I16:\n return 'i16'\n elif ftype == TType.I32:\n return 'i32'\n elif ftype == TType.I64:\n return 'i64'\n elif ftype == TType.STRING:\n return 'string'\n elif ftype == TType.UTF7:\n return 'utf7'\n elif ftype == TType.STRUCT:\n return 'struct'\n elif ftype == TType.MAP:\n return 'map'\n elif ftype == TType.SET:\n return 'set'\n elif ftype == TType.LIST:\n return 'list'\n elif ftype == TType.UTF8:\n return 'utf8'\n elif ftype == TType.UTF16:\n return 'utf16'\n else:\n raise ValueError('Unknown type: %s' % ftype)\n\n\nclass ThriftField(object):\n \"\"\"A thrift field\"\"\"\n\n def __init__(self, field_type, field_id, value):\n self._field_type = field_type\n self._field_id = field_id\n self._value = value\n\n def __eq__(self, other):\n return (isinstance(other, self.__class__)\n and self.__dict__ == other.__dict__)\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __repr__(self):\n return '(%s, %s, %s)' % (\n self.field_type, self.field_id, self._value)\n\n def is_isomorphic_to(self, other):\n \"\"\"\n Returns true if other field's meta data (everything except value)\n is same as this one\n \"\"\"\n return (isinstance(other, self.__class__)\n and self.field_type == other.field_type\n and self.field_id == other.field_id)\n\n @property\n def field_type(self):\n return self._field_type\n\n @property\n def field_id(self):\n return self._field_id\n\n @property\n def value(self):\n return self._value\n\n @property\n def as_dict(self):\n value = self.value.as_dict if hasattr(self.value, 'as_dict') else self.value\n return {\n 'field_id': self.field_id,\n 'field_type': self.field_type,\n 'value': value\n }\n","repo_name":"pinterest/thrift-tools","sub_path":"thrift_tools/thrift_struct.py","file_name":"thrift_struct.py","file_ext":"py","file_size_in_byte":8460,"program_lang":"python","lang":"en","doc_type":"code","stars":227,"dataset":"github-code","pt":"85"} +{"seq_id":"6597294558","text":"def emptyOrNone(s):\n return s is None or len(s.strip()) == 0\n\n\ndef extract_nginx_aware_containers(deltas):\n nothing_to_do = determine_if_noop(deltas)\n if nothing_to_do:\n return []\n containers = {}\n for delta in deltas.deltas:\n delta_op = str(delta.operation)\n deployed = delta.previous if delta_op == \"DESTROY\" else delta.deployed\n container = deployed.container\n if container.hasProperty(\"serverName\") and not emptyOrNone(\n container.serverName) and container.nginxServer is not None:\n if container.name in containers.keys():\n continue\n containers[container.name] = container\n return [containers[ke] for ke in containers.keys()]\n\ndef determine_if_noop(deltas):\n nothing_to_do = True\n for delta in deltas.deltas:\n if str(delta.operation) != \"NOOP\":\n nothing_to_do = False\n break\n return nothing_to_do\n\n\ndef generate_steps(containers, context):\n for container in containers:\n server_name = container.serverName\n upstream_name = container.upstreamName\n api_version = container.apiVersion\n vn = container.nginxServer\n sick_step = steps.jython(description=\"Mark [%s] as down in Nginx [%s], api version is [%s]\" % (server_name, vn.name, api_version), order=5,\n script=\"nginxplus/down-server.py\",\n jython_context={\"server_name\": server_name, \"upstream_name\": upstream_name, \"api_version\": api_version,\n \"nginx_url\": vn.url})\n health_step = steps.jython(description=\"Mark [%s] as up in Nginx [%s], api version is [%s]\" % (server_name, vn.name, api_version), order=95,\n script=\"nginxplus/up-server.py\",\n jython_context={\"server_name\": server_name, \"upstream_name\": upstream_name, \"api_version\": api_version,\n \"nginx_url\": vn.url})\n context.addStep(sick_step)\n context.addStep(health_step)\n\ngenerate_steps(extract_nginx_aware_containers(deltas), context)\n","repo_name":"xebialabs-community/xld-nginx-plus-plugin","sub_path":"src/main/resources/nginxplus/rule.py","file_name":"rule.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27787107728","text":"import cv2\nimport glob\nimport json\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport scipy\nimport tensorflow as tf\nimport time\nfrom detect_flyable_region import flyable_region_detector_hough\n\ntry:\n from object_detection.utils import ops as utils_ops\n from object_detection.utils import visualization_utils as vis_util\n objd_imp = True\nexcept:\n objd_imp = False\n\nfrom queue import Queue\nfrom threading import Thread\nfrom tensorflow.contrib import predictor\n\nfrom scorer.scorer import mAPScorer\nfrom shapely.geometry import Polygon\nfrom tqdm import tqdm\nfrom utils import util_plotting\n\nmatplotlib.use('TKAgg')\n\nCATEGORY_INDEX = {1: {'name': 'gate'}}\n\n# validate this assumption with competition host\nORIGINAL_IMAGE_WIDTH = 1296\nORIGINAL_IMAGE_HEIGHT = 864\n\ncv2.setUseOptimized(True)\nscorer = mAPScorer()\n\nclass MaskRCNNPredictor(object):\n\n def __init__(self, model_dir, image_dir, batch_size=1, prefetch_buffer_size=4, ground_truth_dict=None,\n flyable_region_detector='mask', visualize_hough=False):\n self.model_dir = model_dir\n self.image_dir = image_dir\n self.predict_fn = predictor.from_saved_model(model_dir, config=tf.ConfigProto(log_device_placement=True))\n if ground_truth_dict is None:\n self.all_filenames = glob.glob(os.path.join(image_dir, '*.JPG'))\n else:\n self.all_filenames = list(ground_truth_dict.keys())\n self.batch_size = batch_size\n self.prefetch_buffer_size = prefetch_buffer_size\n self.ground_truth_dict = ground_truth_dict\n self.avg_time = 2 # on average, each image can not exceed 2 sec inference time\n self.flyable_region_detector = flyable_region_detector\n self.visualize_hough = visualize_hough\n\n def predict(self, image_array):\n tic = time.monotonic()\n output_dict = self.predict_fn({'inputs': image_array})\n output_dict = self._reformat_output_dict(output_dict)\n\n # create output array\n output_array = np.zeros(9)\n output_array[-1] = output_dict['detection_scores'][0]\n\n if output_array[-1] > 0.2:\n bbox = output_dict['detection_boxes'][0]\n mask = output_dict['detection_masks'][0, 0, :, :]\n\n if self.flyable_region_detector == 'mask':\n coordinates = self._create_coordinates_from_mask(bbox, mask, img_width=ORIGINAL_IMAGE_WIDTH,\n img_height=ORIGINAL_IMAGE_HEIGHT, image=image_array[0])\n elif self.flyable_region_detector == 'hough':\n image_array_shape = np.shape(image_array[0])\n ymin = int(bbox[0] * image_array_shape[0])\n xmin = int(bbox[1] * image_array_shape[1])\n ymax = int(bbox[2] * image_array_shape[0])\n xmax = int(bbox[3] * image_array_shape[1])\n bbox_hough = {\"y_min\": ymin, \"x_min\": xmin, \"y_max\": ymax, \"x_max\": xmax}\n\n flyable_region_detector = flyable_region_detector_hough(img=image_array[0], bbox=bbox_hough)\n coordinates = flyable_region_detector.detect(visualize=self.visualize_hough)\n\n #In case of failure, use mask\n if len(coordinates) == 0:\n coordinates = self._create_coordinates_from_mask(bbox, mask, img_width=ORIGINAL_IMAGE_WIDTH,\n img_height=ORIGINAL_IMAGE_HEIGHT, image=image_array[0])\n else:\n coordinates = self._create_coordinates_from_mask(bbox, mask, img_width=ORIGINAL_IMAGE_WIDTH,\n img_height=ORIGINAL_IMAGE_HEIGHT, image=image_array[0])\n\n output_array[0:8] = coordinates\n output_array = [output_array.tolist()]\n else:\n output_array = []\n coordinates = []\n\n # store necessary information\n toc = time.monotonic()\n self.time_all.append(toc - tic)\n\n return output_array, coordinates\n\n def run_inference(self, visualize=False, save_img=True):\n # for getting time and predictions\n self.time_all = []\n self.pred_dict = {}\n\n # Get an image tensor and print its value.\n for i in tqdm(range(len(self.all_filenames))):\n cur_filename = self.all_filenames[i]\n cur_filename = os.path.basename(cur_filename)\n\n # generate prediction\n original_image = cv2.imread(os.path.join(self.image_dir, cur_filename))\n original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n image_array = [original_image]\n output_array, coordinates = self.predict(image_array)\n self.pred_dict[cur_filename] = output_array\n\n # visualize original images as well as bounding box\n if len(coordinates):\n if self.ground_truth_dict:\n poly1 = scorer.create_poly(coordinates)\n poly2 = scorer.create_poly(self.ground_truth_dict[cur_filename][0])\n tmp_score = scorer.calculate_iou(poly1, poly2)\n if tmp_score < 0.85:\n print('less than 0.85: %s --- %f', cur_filename, tmp_score)\n\n if len(coordinates):\n if visualize:\n if self.ground_truth_dict:\n if cur_filename in self.ground_truth_dict:\n try:\n util_plotting.plot_GT_pred(image_array[0], [coordinates], self.ground_truth_dict[cur_filename])\n except Exception as e:\n print('failed to plot', cur_filename)\n else:\n util_plotting.plot_bbox(original_image, [coordinates])\n if save_img:\n plt.savefig('tmp/%s' % cur_filename)\n else:\n plt.show()\n plt.close()\n else:\n print('miscatch: %s' % cur_filename)\n\n def _create_coordinates_from_mask(self, bbox, mask, img_width=ORIGINAL_IMAGE_WIDTH, img_height=ORIGINAL_IMAGE_HEIGHT,\n image=None):\n ymin = int(bbox[0] * img_height)\n xmin = int(bbox[1] * img_width)\n ymax = int(bbox[2] * img_height)\n xmax = int(bbox[3] * img_width)\n w = int(xmax - xmin)\n h = int(ymax - ymin)\n\n # resize mask back to the bbox size and use bbox coordinate as reference\n mask = scipy.misc.imresize((mask > 0.2).astype(np.uint8), (h, w), interp='nearest')\n\n # convert mask to threshold and find contour\n ret, thresh = cv2.threshold(mask, 0.5, 1, 0)\n\n # OpenCV 3.x\n # _, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # OpenCV 4.x\n contours, _ = cv2.findContours(thresh.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n # generate approximate polygon, this should be rectangle most of the time\n epsilon = 0.025 * cv2.arcLength(contours[0], True)\n hull = cv2.convexHull(contours[0])\n approx = cv2.approxPolyDP(hull, epsilon, True)\n\n if approx.size != 8:\n # if approxPolyDP does not generate a rectangle, fit a simple rectangle\n rect = cv2.minAreaRect(contours[0])\n approx = cv2.boxPoints(rect)\n approx[:, 0] = approx[:, 0] + xmin\n approx[:, 1] = approx[:, 1] + ymin\n\n else:\n approx[:, 0, 0] = approx[:, 0, 0] + xmin\n approx[:, 0, 1] = approx[:, 0, 1] + ymin\n\n new_mask = np.zeros((img_height, img_width))\n new_mask[ymin:(ymin + h), xmin:(xmin + w)] = mask\n\n \"\"\"\n image = image[ymin:(ymin + h), xmin:(xmin + w), :]\n sure_fg = (mask > 0.9).astype(np.uint8)\n ret, markers = cv2.connectedComponents(sure_fg)\n #markers = (1 + (mask > 0.5)).astype(np.int32)\n markers = cv2.watershed(image, markers)\n image[markers == -1] = [255, 0, 0]\n plt.imshow(image)\n plt.imshow(mask, alpha=0.4)\n plt.show()\n plt.close()\n \"\"\"\n\n # DO NOT REMOVE, FOR DEBUGGING\n \"\"\"\n new_mask = np.zeros((img_height, img_width))\n new_mask[ymin:(ymin + h), xmin:(xmin + w)] = mask\n\n plt.imshow(image[ymin:(ymin + h), xmin:(xmin + w), :])\n plt.imshow(mask, alpha=0.4)\n plt.show()\n plt.close()\n \"\"\"\n return approx.flatten()\n\n def _create_coordinates(self, bbox, img_width=ORIGINAL_IMAGE_WIDTH, img_height=ORIGINAL_IMAGE_HEIGHT):\n \"\"\"Create required output array.\n\n Assume only one gate in the image, so the highest probability bounding box is taken.\n\n :param bbox: Normalized bounding box\n :return:\n \"\"\"\n ymin = bbox[0] * img_height\n xmin = bbox[1] * img_width\n ymax = bbox[2] * img_height\n xmax = bbox[3] * img_width\n return np.array([xmin, ymin, xmin, ymax, xmax, ymax, xmax, ymin]).astype(np.int)\n\n def _reformat_output_dict(self, output_dict):\n \"\"\"Extract first element out and convert to desired data type.\n\n :param output_dict: A dict with detection outputs\n :return: Reformatted dict\n \"\"\"\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n\n return output_dict\n\n def _visualize_image_with_bbox(self, image_array, output_dict, title=None):\n \"\"\"Plot image with bounding box\n\n :param image_array: A numpy array\n :param output_dict: A dict with reformatted detection outputs\n :param title: Filename\n :return: None\n \"\"\"\n if self.batch_size == 1 and objd_imp:\n # currently only handle cases when batch size is equal to 1\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_array,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n CATEGORY_INDEX,\n use_normalized_coordinates=True,\n line_thickness=8)\n plt.figure()\n plt.imshow(image_array)\n if title:\n plt.title(title)\n plt.show()\n\n def output_submission_file(self, output_filename='final_submission.json'):\n avg_time = np.mean(self.time_all)\n ci_time = 1.96 * np.std(self.time_all)\n print('Time stats -- Mean: %f, Std: %f' % (avg_time, ci_time))\n with open(output_filename, 'w') as f:\n json.dump(self.pred_dict, f)\n self.avg_time = avg_time\n\n\nif __name__ == '__main__':\n model_dir = 'weights/maskrcnn-inception-v2'\n image_dir = 'training/small'\n img_predictor = MaskRCNNPredictor(model_dir, image_dir, batch_size=1)\n img_predictor.run_inference(visualize=True)\n img_predictor.output_submission_file(output_filename='submission_maskrcnn_all.json')\n","repo_name":"randxie/alpha-pilot-team-deadlock","sub_path":"vision/final_code/maskrcnn_predictor.py","file_name":"maskrcnn_predictor.py","file_ext":"py","file_size_in_byte":10214,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"8673014227","text":"from src.ufu_parser import UfuParser\nfrom src.ufu_parser.parser_observer import Observer, ObserverBuilder\nfrom src.ufu_parser.syntax_tree import SyntaxNode\nfrom src.ufu_parser.syntactic_graphs.componets import *\nfrom .scope_detection import ScopeDetection\nfrom src.ufu_token import UfuTokenType\nfrom typing import Optional\nfrom src.symbol_tables import Symbol\n\n\nclass ScopeDetectionPlugin:\n scope_detection: ScopeDetection\n\n def __init__(self):\n self.scope_detection = ScopeDetection()\n\n def __on_create_block(self, node: SyntaxNode):\n self.scope_detection.new_scope(name=f\"block:{id(node)}\")\n\n def __on_complete_block(self, _: SyntaxNode):\n self.scope_detection.back_scope()\n \"\"\"\n ao final de um símbolo não terminal bloco\n o escopo atual volta para o seu antecessor se\n não houver antecessor ,então o escopo é o Global e não há o que voltar.\n \"\"\"\n\n def __on_complete_variable_declaration(self, node: SyntaxNode):\n information: dict = node.information\n variable_type = information.get(UfuTokenType.TYPE_VARIABLE.value)\n ids = information.get(UfuTokenType.ID.value)\n \"\"\"\n um símbolo não terminal DeclaracaoDeVariavel deriva em:\n DeclaracaoDeVariavel → TipoDeVariavel : listaIds ;\n logo o seu nó deve conter o tipo da ou das variáveis e uma lista de ids\n informações essas que viram símbolos da tabela do escopo atual\n \n \"\"\"\n\n for variable_id in ids:\n self.scope_detection.insert_symbol_on_current_scope(Symbol(variable_type, variable_id, ''))\n\n def __verify_id(self, node: SyntaxNode):\n information: dict = node.information\n\n variable_id: Optional[str] = information.get(UfuTokenType.ID.value)\n \"\"\"\n um node pode ou não conter um uma variável ID\n como no caso do símbolo não terminal Fator,\n Fator -> id | ConstInt | ConstReal\n ou seja, possa ser que esse nó derive em um ID \n \"\"\"\n if not variable_id:\n return\n\n self.scope_detection.verify_variable_declaration(variable_id)\n\n def build(self, parser: UfuParser):\n block_observer = ObserverBuilder() \\\n .set_on_create(self.__on_create_block) \\\n .set_on_complete(self.__on_complete_block) \\\n .build()\n\n parser.register_observer(Bloco, block_observer)\n\n variable_declaration_observer = ObserverBuilder() \\\n .set_on_complete(self.__on_complete_variable_declaration) \\\n .build()\n\n parser.register_observer(DeclaracaoDeVariavel, variable_declaration_observer)\n\n verify_id_observer = ObserverBuilder() \\\n .set_on_complete(self.__verify_id) \\\n .build()\n\n \"\"\"cmdAtribuicao → id:=hexpressaoAritmeticaOuConstAsciii;\"\"\"\n parser.register_observer(CmdAtribuicao, verify_id_observer)\n\n \"\"\"fator → id | ConstInt | ConstReal |(expressaoAritmetica)\"\"\"\n parser.register_observer(Fator, verify_id_observer)\n\n \"idOUConstante → id | ConstInt | ConstReal | ConstAscii\"\n parser.register_observer(IdOuConstante, verify_id_observer)\n","repo_name":"samuel-cavalcanti/ufu_language_ufu","sub_path":"src/scope_detection/scope_detection_parser_plugin.py","file_name":"scope_detection_parser_plugin.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"21115738179","text":"import json\nimport os\nfrom typing import Any, Dict, List, Optional\n\nfrom labmachine.base import DNSSpec\nfrom labmachine.types import DNSRecord, DNSZone\nfrom libcloud.dns.base import Record, Zone\nfrom libcloud.dns.providers import get_driver\nfrom libcloud.dns.types import Provider, RecordDoesNotExistError\n\nfrom .common import GOOGLE_AUTH_ENV, GCConf, get_auth_conf\n\n\nclass GoogleDNS(DNSSpec):\n providerid = \"gce\"\n\n def __init__(self, keyvar: str = GOOGLE_AUTH_ENV):\n super().__init__(keyvar=keyvar)\n conf = get_auth_conf(env_var=keyvar)\n G = get_driver(Provider.GOOGLE)\n\n self._project = conf.PROJECT\n self._account = conf.SERVICE_ACCOUNT\n\n self.driver = G(\n conf.SERVICE_ACCOUNT,\n conf.CREDENTIALS,\n project=conf.PROJECT,\n )\n\n def list_zones(self) -> List[DNSZone]:\n zs = self.driver.list_zones()\n zones = [DNSZone(\n id=z.id,\n domain=z.domain,\n zone_type=z.type,\n ttl=z.ttl,\n ) for z in zs]\n return zones\n\n def create_zone(self, zone: DNSZone):\n z = self.driver.create_zone(\n domain=zone.domain,\n type=zone.zone_type,\n ttl=zone.ttl,\n extra=zone.extra\n )\n return z\n\n def get_zone(self, zoneid: str) -> DNSZone:\n z = self.driver.get_zone(zoneid)\n return self._data2zone(z)\n\n def delete_zone(self, zoneid: str):\n pass\n\n def _data2record(self, r: Record) -> DNSRecord:\n _id = f\"{r.type}:{r.name}\"\n return DNSRecord(\n id=_id,\n name=r.name,\n zoneid=r.zone.id,\n record_type=r.type,\n data=r.data[\"rrdatas\"]\n )\n\n def _data2zone(self, z: Zone) -> DNSZone:\n return DNSZone(\n domain=z.domain,\n zone_type=z.type,\n ttl=z.ttl,\n id=z.id,\n )\n\n def get_record(self, zoneid: str, recordid: str) -> DNSRecord:\n r = self.driver.get_record(zoneid, recordid)\n return self._data2record(r)\n\n def list_records(self, zoneid: str) -> List[DNSRecord]:\n z = self.driver.get_zone(zoneid)\n rs = self.driver.list_records(z)\n records = [self._data2record(r) for r in rs]\n return records\n\n def create_record(self, record: DNSRecord) -> Dict[str, Any]:\n z = self.driver.get_zone(record.zoneid)\n r = self.driver.create_record(\n record.name,\n z,\n type=record.record_type,\n data={\n \"rrdatas\": record.data,\n \"type\": record.record_type,\n \"ttl\": record.ttl\n }\n )\n record.id = r.id\n return record.dict()\n\n def delete_record(self, zoneid: str, recordid: str) -> bool:\n \"\"\" \"A:testlib.dymax.app.\"\"\"\n try:\n r = self.driver.get_record(zoneid, recordid)\n deleted = self.driver.delete_record(r)\n except RecordDoesNotExistError:\n return False\n return deleted\n","repo_name":"nuxion/labmachine","sub_path":"labmachine/providers/google/dns.py","file_name":"dns.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73401624919","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n# 更好的方法是为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能:\nfrom enum import Enum, unique\n\nMonth = Enum('month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))\nprint(Month)\n\n# 这样我们就获得了Month类型的枚举类,可以直接使用Month.Jan来引用一个常量,或者枚举它的所有成员:\nfor name, member in Month.__members__.items():\n print(name, '=>', member, ',', member.value)\n\n\n@unique\nclass Weekday(Enum):\n Sun = 0 # Sun的value被设定为0\n Mon = 1\n Tue = 2\n Wed = 3\n Thu = 4\n Fri = 5\n Sat = 6\n\n\n# @unique装饰器可以帮助我们检查保证没有重复值。\n# 访问这些枚举类型可以有若干种方法:\n# 方式一\nday1 = Weekday.Sun\nprint(day1)\n\n# 方式二\nday3 = Weekday['Tue']\nprint(day3)\n\n# 获取值\nday3val = Weekday.Tue.value\nprint(day3val)\n","repo_name":"MrWJB/rtxs","sub_path":"rtxs/复习/枚举类复习.py","file_name":"枚举类复习.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34844777427","text":"class Solution(object):\n def relativeSortArray(self, arr1, arr2):\n a=[]*len(arr1)\n for i in arr2:\n x=arr1.count(i)\n for j in range(x):\n a.append(i)\n b=[]\n [b.append(i) for i in arr1 if i not in arr2]\n b.sort()\n return a+b","repo_name":"SyamKrishnaReddyPulagam/DSA","sub_path":"1122-relative-sort-array/1122-relative-sort-array.py","file_name":"1122-relative-sort-array.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18192665822","text":"from flask import Blueprint\n\nfrom fructify.auth import oauth\n\n\nbp = Blueprint(\"googlecalendars\", __name__)\n\n\n@bp.route(\"/api/v1/googlecalendars\")\ndef googlecalendars():\n response = oauth.google.get(\n \"https://www.googleapis.com/calendar/v3/users/me/calendarList\"\n )\n response.raise_for_status()\n return {\n \"googleCalendars\": [\n {\"id\": calendar[\"id\"], \"summary\": calendar[\"summary\"]}\n for calendar in response.json()[\"items\"]\n if calendar[\"accessRole\"] == \"owner\"\n ]\n }\n","repo_name":"fffergal/fructify","sub_path":"fructify/blueprints/googlecalendars.py","file_name":"googlecalendars.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7148303305","text":"import requests\nimport json\n\nwhile True:\n num_jogadores = input(\"Quantos jogadores vão jogar? (1-4): \")\n if num_jogadores.isdigit() and 1 <= int(num_jogadores) <= 4:\n num_jogadores = int(num_jogadores)\n break\n else:\n print(\"Por favor, insira um número entre 1 e 4.\")\n \nvalor = input('Insira o valor da carta: ').upper()\n\n\ndicionario_naipes = {\n 'COPAS': 'HEARTS',\n 'PAUS': 'CLUBS',\n 'ESPADAS': 'SPADES',\n 'OUROS': 'DIAMONDS',\n 'HEARTS': 'COPAS',\n 'CLUBS': 'PAUS',\n 'SPADES': 'ESPADAS',\n 'DIAMONDS': 'OUROS'\n}\n\nnaipe = input('informe o naipe desejado: ').upper()\n \nresponse_baralho = requests.get('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')\n\nbaralho = response_baralho.json()\ndeck_id = baralho['deck_id']\n\nwhile True:\n response_carta = requests.get(f'https://deckofcadsapi.com/api/deck/{deck_id}/draw/?count=1')\n carta = response_carta.json()['cards'][0]\n cartas_no_baralho = response_carta.json()['remaining']\n \n if carta['value'] == valor and carta['suit'] == dicionario_naipes[naipe]:\n print('\\n\\nEncontrei sua carta!')\n \n codigo = carta['code']\n with open('carta.json','w') as arquivo_carta:\n json.dump(carta, arquivo_carta)\n \n break\n else:\n valor_encontrado = carta['value']\n naipe_encontrado = dicionario_naipes[carta['suit']]\n print(f'Carta encontrada: {valor_encontrado} de {naipe_encontrado}')\n print(f'Cartas restantes no baralho: {cartas_no_baralho}\\n')\n ","repo_name":"GabrielOliveira7/Codigos-Gabriel","sub_path":"Estudo Python/Exercícios/eXERCICIO DE FIXAÇÃO BLACKJACK.PY","file_name":"eXERCICIO DE FIXAÇÃO BLACKJACK.PY","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"36618353605","text":"class ProjectToken:\n def __init__(self, modified, productLineCode, productLine, releaseType, release, langCodeName, mediaType, languageAva, fiscalYear, RTMDate, RTPDate, RTWDate, FCSDate, Quarter):\n self.modified = modified\n self.productLineCode = productLineCode\n self.productLine = productLine\n self.releaseType = releaseType\n self.mediaType = mediaType\n self.languageAvaliable = languageAva\n self.fiscalYear = fiscalYear\n self.release = release\n self.langCodeName = langCodeName\n self.RTMDate = RTMDate\n self.RTPDate = RTPDate\n self.RTWDate = RTWDate\n self.FCSDate = FCSDate\n self.Quarter = Quarter\n\n","repo_name":"JamezMing/flaskChatbot","sub_path":"app/ProjectToken.py","file_name":"ProjectToken.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21564018783","text":"import sys\nsys.stdin = open('input.txt')\n\n# thought process: 2분 59초\n# 하나씩 대조, 일치하면 target idx 증가 후 대조 반복\n# 틀리면 타겟 인덱스 초기화 & 전체 인덱스 한칸 전진 후 다시 대조 시작\n# target idx 끝까지 가면, 일치하니, 바로 루프 return 1\n# 루프를 나와버리면 없다는뜻이니 return 0\n\n# 소요시간 12분 4초\ndef checker():\n for i in range(f-t+1):\n for j in range(t):\n if target[j] != full[i + j]:\n break\n elif j == t - 1:\n return 1\n return 0\n\nfor tc in range(1, int(input())+1):\n target = input()\n full = input()\n t = len(target)\n f = len(full)\n print('#{} {}'.format(tc, checker()))\n\n# 소요시간: 4분35초\n# for tc in range(1, int(input())+1):\n# target = input()\n# main_str = input()\n#\n# if target in main_str:\n# print(1)\n# else:\n# print(0)\n","repo_name":"SPlCYWOLF/algorithm-practices","sub_path":"python/SWEA/210923/4864_문자열비교/s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"666247887","text":"\"\"\"\r\nThis module explain the Python statement and comments\r\n\"\"\"\r\n# Python Statement\r\n\r\n#In Python.\r\n\r\n#End of a statement is marked by a new line character.\r\n#But we can make a statment extend over multiple lines\r\n#with the line continuation character(\\).\r\n\r\n#For example\r\na=1+2+3\\\r\n +4+5+6+\\\r\n 7+8+9\r\nprint(a) # 45\r\nprint('a type: '+str(type(a)))\r\n\r\n#The above is explicit line continuation\r\n# We can also use (),[],{} \r\n\r\n# ()\r\nb=(1+2+3+4\r\n +5+6+7+8\r\n +9)\r\n\r\nprint(b) # 45\r\nprint('b type: '+str(type(b)))\r\n\r\n# [], it is actually forming a list\r\nc=[1+2+3+4\r\n +5+6+7+8\r\n +9]\r\nprint(c) #[45]\r\nprint('c type: '+str(type(c)))\r\n\r\n# {}, it is actuall forming a set\r\nd={1+2+3+4\r\n +5+6+7+8\r\n +9}\r\nprint(d) # {45}\r\nprint('d type: '+str(type(d)))\r\n\r\n# [] with string \r\ncolors = ['red'\r\n 'blue'\r\n 'green']\r\nprint(colors)\r\nprint('colors type: '+str(type(colors)))\r\n\r\n\r\n# Comment\r\n'''This is also a\r\nperfect example of\r\nmulti-line comments'''\r\n","repo_name":"hyzlt7980/Python","sub_path":"Python Elementary/Python_Statement_Comments.py","file_name":"Python_Statement_Comments.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"72020444759","text":"\"\"\"\nglobal settings for mini_spider project\n\nAuthor: Lei Wang (yiak.wy@gmail.com)\nDate: 2017/11/22\n\"\"\"\n\nimport sys\nimport os\n\n# Root path will be compute dynamically in runtime\n\n# downlaoder\nTIME_OUT=15\n\n# mail \nMAIL_ADDR=[\"mail.x.com\", \"devops@x.com\", \"notify@x.com\"]\nMAIL_CREDENTIALS=[\"devops@x.com\", \"password\"]\nMAIL_HOSTS=\"localhost\"\n\nLOG_DIR = './log/'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': \"%(asctime)s [%(levelname)s]:%(filename)s, %(name)s, in line %(lineno)s >> %(message)s\",\n 'datefmt': \"%a, %d, %b, %Y %H:%M:%S\", #\"%d/%b/%Y %H:%M:%S\"\n }\n # add different formattrs here\n },\n 'handlers': {\n 'console': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout,\n 'formatter': 'verbose'\n },\n 'email_remote': {\n 'level': 'ERROR',\n 'class': 'logging.handlers.SMTPHandler',\n 'formatter': 'verbose',\n 'mailhost': MAIL_HOSTS,\n 'fromaddr': 'mini_spider_notify@yiak.co',\n 'toaddrs': MAIL_ADDR,\n 'subject': 'mini spider project ERROR!',\n 'credentials': MAIL_CREDENTIALS\n\n },\n 'file': {\n 'level': 'INFO',\n 'class': 'logging.FileHandler',\n 'formatter':'verbose',\n 'filename': os.path.join(LOG_DIR, 'mini_spider.log')\n }\n\n },\n 'loggers': {\n 'downloader/handlers/async_socket_http11': {\n 'handlers': ['console', 'file'],\n 'propagate': True,\n 'level': 'INFO'\n },\n 'spiders': {\n 'handlers': ['console', 'file'],\n 'propagate': True,\n 'level': 'INFO'\n },\n 'base_spider': {\n 'handlers': ['console', 'file'],\n 'propagate': True,\n 'level': 'INFO'\n }\n }\n}\n\n# HTTPS support\nCERT_FILE = '/etc/ssl/certs/ca-certificates.crt'\n\n# see see https://github.com/python/cpython/blob/master/Lib/test/test_ssl.py for supported (tested) cipher algorithms\nCHIPHER = 'AES128-GCM-SHA256'\n\n# Webkit support\nJsInjRoot = \"/home/yiakwy/WorkSpace/Bitbucket/mini_spider/remote_inj_js_call_wireless_protocol\"","repo_name":"yiakwy/light_async_spider","sub_path":"config/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"14255372000","text":"import face_recognition\nimport os\nimport cv2 as cv\nimport pickle\nfrom django.conf import settings\n\n## Dada una imagen, extrae la cara de mayor tamaño en ella\ndef detectMainFaceCoordinates(frame):\n\n faces = []\n biggerFace = {\"x\":0, \"y\":0, \"w\":0, \"h\":0}\n\n face_locations = face_recognition.face_locations(frame)\n\n for (top, right, bottom, left) in face_locations:\n faces.append([left, top, right-left, bottom - top])\n\n \n for (x,y,w,h) in faces:\n if (biggerFace[\"w\"] * biggerFace[\"h\"]) < (w * h):\n biggerFace[\"x\"], biggerFace[\"y\"], biggerFace[\"w\"], biggerFace[\"h\"] = x, y, w, h\n\n if len(faces) == 0:\n return None\n\n return biggerFace\n\n## Dada una imagen, extrae la cara principal y la guarda en tmpImagesPath\ndef parseImage(rawImagePath, tmpImagesPath):\n\n ret = False\n\n image = face_recognition.load_image_file(rawImagePath)\n\n mainFaceCoordinates = detectMainFaceCoordinates(image)\n\n if mainFaceCoordinates is not None: # if a face has been found\n\n cvImage = cv.imread(rawImagePath)\n\n mainFace = cvImage[mainFaceCoordinates[\"y\"]:mainFaceCoordinates[\"y\"]+mainFaceCoordinates[\"h\"],mainFaceCoordinates[\"x\"]:mainFaceCoordinates[\"x\"]+mainFaceCoordinates[\"w\"]]\n faceDimentions = (260,260)\n mainFace = cv.resize(mainFace, faceDimentions)\n\n id = len(os.listdir(tmpImagesPath)) + 1\n cv.imwrite(os.path.join(tmpImagesPath, str(id) + \".jpg\"), mainFace)\n ret = True\n\n return ret\n\n## Dadas una serie de imágenes, se crea un reconocedor en recognizerPath\ndef createRecognizer(imagesPath, recognizerPath):\n\n known_encodings = []\n\n for imagePath in os.listdir(imagesPath):\n\n imgPath = os.path.join(imagesPath, imagePath)\n \n known_image = face_recognition.load_image_file(imgPath)\n known_encoding = face_recognition.face_encodings(known_image)\n \n if known_encoding: \n known_encodings.append(known_encoding[0])\n\n f = open(recognizerPath, 'wb')\n pickle.dump(known_encodings, f)\n f.close()\n\n return True\n\n## Dado un reconocedor y unas imágenes, se devuelve el veredicto del reconocedor\ndef recognize(recognizerPath, imagesPath):\n\n numRecognizedImages = 0\n\n betterImg = [0, None]\n \n ## Cargar el reconocedor\n f = open(recognizerPath, 'rb')\n knownEncodings = pickle.load(f)\n f.close()\n\n ## Reconocer las imágenes con el reconocedor\n for img in os.listdir(imagesPath):\n\n imgPath = os.path.join(imagesPath, img)\n\n image = face_recognition.load_image_file(imgPath)\n\n unknown_encoding = face_recognition.face_encodings(image)\n\n if len(unknown_encoding) == 1:\n results = face_recognition.compare_faces(knownEncodings, unknown_encoding[0], tolerance=0.6)\n numFalses = 0\n numTrues = 0\n\n for result in results:\n if result:\n numTrues += 1\n else:\n numFalses += 1\n\n if numFalses > len(knownEncodings) * settings.RECOGNIZE_TOLERANCE:\n pass\n else:\n if betterImg[0] < numTrues:\n betterImg[0] = numTrues\n betterImg[1] = unknown_encoding[0]\n numRecognizedImages += 1\n\n\n ret = numRecognizedImages >= settings.RECOGNIZE_MIN_VALID_IMGS\n\n ## Actualizar el reconocedor con una imágen usada para el inicio de sesión\n if ret:\n\n if len(knownEncodings) >= settings.MAX_MODEL_IMAGES:\n del knownEncodings[0]\n \n knownEncodings.append(betterImg[1])\n f = open(recognizerPath, 'wb')\n pickle.dump(knownEncodings, f)\n f.close()\n\n return ret","repo_name":"Arkh3/TFG_repo","sub_path":"FaceRecognitionDeployment/fr_project/authentication/faceRecognition.py","file_name":"faceRecognition.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"39292912912","text":"import pika\nimport csv\n\ndef callback(ch, method, properties, body):\n \"\"\"\n Callback function to consume messages from the RabbitMQ queue.\n\n Param ch: Channel object\n Param method: Method object\n Param properties: Properties object\n Param body: Message body\n \"\"\"\n message = body.decode('utf-8')\n headers = [key for key in json.loads(message).keys()]\n preds = json.loads(message)['data']['preds']\n with open('/output/predictions.csv', mode='a') as file:\n writer = csv.writer(file)\n if file.tell() == 0:\n writer.writerow(headers)\n for pred in preds:\n row = [json.loads(message)[key] if key != 'preds' else pred[key] for key in headers]\n writer.writerow(row)\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\ndef consume_messages():\n \"\"\"\n Consume messages from the RabbitMQ queue.\n \"\"\"\n try:\n connection = pika.BlockingConnection(pika.ConnectionParameters(host='rabbitmq'))\n channel = connection.channel()\n channel.queue_declare(queue='predictions')\n channel.basic_qos(prefetch_count=1)\n channel.basic_consume(queue='predictions', on_message_callback=callback)\n channel.start_consuming()\n except:\n pass\n\nif __name__ == '__main__':\n # Example\n consume_messages()","repo_name":"hadihafiz/take-home-assestment","sub_path":"consumer/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29733626618","text":"import bisect\nimport logging\nimport re\nimport typing\nfrom abc import ABC, abstractmethod\nfrom collections import Counter, defaultdict\nfrom operator import itemgetter\nfrom pathlib import Path\nfrom typing import Dict, Iterable, List, NamedTuple, Optional, Union, cast\n\nimport torch\nfrom deprecated.sphinx import deprecated\nfrom torch.utils.data import Dataset, IterableDataset\nfrom torch.utils.data.dataset import ConcatDataset, Subset\n\nimport flair\nfrom flair.file_utils import Tqdm\nfrom flair.tokenization import SegtokTokenizer, SpaceTokenizer, Tokenizer\n\nT_co = typing.TypeVar(\"T_co\", covariant=True)\n\nlog = logging.getLogger(\"flair\")\n\n\ndef _iter_dataset(dataset: Optional[Dataset]) -> typing.Iterable:\n if dataset is None:\n return []\n from flair.datasets import DataLoader\n\n return (x[0] for x in DataLoader(dataset, batch_size=1))\n\n\ndef _len_dataset(dataset: Optional[Dataset]) -> int:\n if dataset is None:\n return 0\n from flair.datasets import DataLoader\n\n loader = DataLoader(dataset, batch_size=1)\n return len(loader)\n\n\nclass BoundingBox(NamedTuple):\n left: str\n top: int\n right: int\n bottom: int\n\n\nclass Dictionary:\n \"\"\"This class holds a dictionary that maps strings to IDs, used to generate one-hot encodings of strings.\"\"\"\n\n def __init__(self, add_unk=True) -> None:\n # init dictionaries\n self.item2idx: Dict[bytes, int] = {}\n self.idx2item: List[bytes] = []\n self.add_unk = add_unk\n self.multi_label = False\n self.span_labels = False\n # in order to deal with unknown tokens, add \n if add_unk:\n self.add_item(\"\")\n\n def remove_item(self, item: str):\n bytes_item = item.encode(\"utf-8\")\n if bytes_item in self.item2idx:\n self.idx2item.remove(bytes_item)\n del self.item2idx[bytes_item]\n\n def add_item(self, item: str) -> int:\n \"\"\"Add string - if already in dictionary returns its ID. if not in dictionary, it will get a new ID.\n\n Args:\n item: a string for which to assign an id.\n\n Returns: ID of string\n \"\"\"\n bytes_item = item.encode(\"utf-8\")\n if bytes_item not in self.item2idx:\n self.idx2item.append(bytes_item)\n self.item2idx[bytes_item] = len(self.idx2item) - 1\n return self.item2idx[bytes_item]\n\n def get_idx_for_item(self, item: str) -> int:\n \"\"\"Returns the ID of the string, otherwise 0.\n\n Args:\n item: string for which ID is requested\n\n Returns: ID of string, otherwise 0\n \"\"\"\n item_encoded = item.encode(\"utf-8\")\n if item_encoded in self.item2idx:\n return self.item2idx[item_encoded]\n elif self.add_unk:\n return 0\n else:\n log.error(f\"The string '{item}' is not in dictionary! Dictionary contains only: {self.get_items()}\")\n log.error(\n \"You can create a Dictionary that handles unknown items with an -key by setting add_unk = True in the construction.\"\n )\n raise IndexError\n\n def get_idx_for_items(self, items: List[str]) -> List[int]:\n \"\"\"Returns the IDs for each item of the list of string, otherwise 0 if not found.\n\n Args:\n items: List of string for which IDs are requested\n\n Returns: List of ID of strings\n \"\"\"\n if not hasattr(self, \"item2idx_not_encoded\"):\n d = {key.decode(\"UTF-8\"): value for key, value in self.item2idx.items()}\n self.item2idx_not_encoded = defaultdict(int, d)\n\n if not items:\n return []\n results = itemgetter(*items)(self.item2idx_not_encoded)\n if isinstance(results, int):\n return [results]\n return list(results)\n\n def get_items(self) -> List[str]:\n items = []\n for item in self.idx2item:\n items.append(item.decode(\"UTF-8\"))\n return items\n\n def __len__(self) -> int:\n return len(self.idx2item)\n\n def get_item_for_index(self, idx):\n return self.idx2item[idx].decode(\"UTF-8\")\n\n def set_start_stop_tags(self):\n self.add_item(\"\")\n self.add_item(\"\")\n\n def is_span_prediction_problem(self) -> bool:\n if self.span_labels:\n return True\n return any(item.startswith((\"B-\", \"S-\", \"I-\")) for item in self.get_items())\n\n def start_stop_tags_are_set(self) -> bool:\n return {b\"\", b\"\"}.issubset(self.item2idx.keys())\n\n def save(self, savefile):\n import pickle\n\n with open(savefile, \"wb\") as f:\n mappings = {\"idx2item\": self.idx2item, \"item2idx\": self.item2idx}\n pickle.dump(mappings, f)\n\n def __setstate__(self, d):\n self.__dict__ = d\n # set 'add_unk' if the dictionary was created with a version of Flair older than 0.9\n if \"add_unk\" not in self.__dict__:\n self.__dict__[\"add_unk\"] = b\"\" in self.__dict__[\"idx2item\"]\n\n @classmethod\n def load_from_file(cls, filename: Union[str, Path]):\n import pickle\n\n with Path(filename).open(\"rb\") as f:\n mappings = pickle.load(f, encoding=\"latin1\")\n idx2item = mappings[\"idx2item\"]\n item2idx = mappings[\"item2idx\"]\n\n # set 'add_unk' depending on whether is a key\n add_unk = b\"\" in idx2item\n\n dictionary: Dictionary = Dictionary(add_unk=add_unk)\n dictionary.item2idx = item2idx\n dictionary.idx2item = idx2item\n return dictionary\n\n @classmethod\n def load(cls, name: str):\n from flair.file_utils import cached_path\n\n hu_path: str = \"https://flair.informatik.hu-berlin.de/resources/characters\"\n if name == \"chars\" or name == \"common-chars\":\n char_dict = cached_path(f\"{hu_path}/common_characters\", cache_dir=\"datasets\")\n return Dictionary.load_from_file(char_dict)\n\n if name == \"chars-large\" or name == \"common-chars-large\":\n char_dict = cached_path(f\"{hu_path}/common_characters_large\", cache_dir=\"datasets\")\n return Dictionary.load_from_file(char_dict)\n\n if name == \"chars-xl\" or name == \"common-chars-xl\":\n char_dict = cached_path(f\"{hu_path}/common_characters_xl\", cache_dir=\"datasets\")\n return Dictionary.load_from_file(char_dict)\n\n if name == \"chars-lemmatizer\" or name == \"common-chars-lemmatizer\":\n char_dict = cached_path(f\"{hu_path}/common_characters_lemmatizer\", cache_dir=\"datasets\")\n return Dictionary.load_from_file(char_dict)\n\n return Dictionary.load_from_file(name)\n\n def __eq__(self, o: object) -> bool:\n if not isinstance(o, Dictionary):\n return False\n return self.item2idx == o.item2idx and self.idx2item == o.idx2item and self.add_unk == o.add_unk\n\n def __str__(self) -> str:\n tags = \", \".join(self.get_item_for_index(i) for i in range(min(len(self), 50)))\n return f\"Dictionary with {len(self)} tags: {tags}\"\n\n\nclass Label:\n \"\"\"This class represents a label.\n\n Each label has a value and optionally a confidence score. The score needs to be between 0.0 and 1.0.\n Default value for the score is 1.0.\n \"\"\"\n\n def __init__(self, data_point: \"DataPoint\", value: str, score: float = 1.0) -> None:\n self._value = value\n self._score = score\n self.data_point: DataPoint = data_point\n super().__init__()\n\n def set_value(self, value: str, score: float = 1.0):\n self._value = value\n self._score = score\n\n @property\n def value(self) -> str:\n return self._value\n\n @property\n def score(self) -> float:\n return self._score\n\n def to_dict(self):\n return {\"value\": self.value, \"confidence\": self.score}\n\n def __str__(self) -> str:\n return f\"{self.data_point.unlabeled_identifier}{flair._arrow}{self._value} ({round(self._score, 4)})\"\n\n @property\n def shortstring(self):\n return f'\"{self.data_point.text}\"/{self._value}'\n\n def __repr__(self) -> str:\n return f\"'{self.data_point.unlabeled_identifier}'/'{self._value}' ({round(self._score, 4)})\"\n\n def __eq__(self, other):\n return self.value == other.value and self.score == other.score and self.data_point == other.data_point\n\n def __hash__(self):\n return hash(self.__repr__())\n\n def __lt__(self, other):\n return self.data_point < other.data_point\n\n @property\n def labeled_identifier(self):\n return f\"{self.data_point.unlabeled_identifier}/{self.value}\"\n\n @property\n def unlabeled_identifier(self):\n return f\"{self.data_point.unlabeled_identifier}\"\n\n\nclass DataPoint:\n \"\"\"This is the parent class of all data points in Flair.\n\n Examples for data points are Token, Sentence, Image, etc.\n Each DataPoint must be embeddable (hence the abstract property embedding() and methods to() and clear_embeddings()).\n Also, each DataPoint may have Labels in several layers of annotation (hence the functions add_label(), get_labels()\n and the property 'label')\n \"\"\"\n\n def __init__(self) -> None:\n self.annotation_layers: Dict[str, List[Label]] = {}\n self._embeddings: Dict[str, torch.Tensor] = {}\n self._metadata: Dict[str, typing.Any] = {}\n\n @property\n @abstractmethod\n def embedding(self):\n pass\n\n def set_embedding(self, name: str, vector: torch.Tensor):\n self._embeddings[name] = vector\n\n def get_embedding(self, names: Optional[List[str]] = None) -> torch.Tensor:\n # if one embedding name, directly return it\n if names and len(names) == 1:\n if names[0] in self._embeddings:\n return self._embeddings[names[0]].to(flair.device)\n else:\n return torch.tensor([], device=flair.device)\n\n # if multiple embedding names, concatenate them\n embeddings = self.get_each_embedding(names)\n if embeddings:\n return torch.cat(embeddings, dim=0)\n else:\n return torch.tensor([], device=flair.device)\n\n def get_each_embedding(self, embedding_names: Optional[List[str]] = None) -> List[torch.Tensor]:\n embeddings = []\n for embed_name in sorted(self._embeddings.keys()):\n if embedding_names and embed_name not in embedding_names:\n continue\n embed = self._embeddings[embed_name].to(flair.device)\n embeddings.append(embed)\n return embeddings\n\n def to(self, device: str, pin_memory: bool = False):\n for name, vector in self._embeddings.items():\n if str(vector.device) != str(device):\n if pin_memory:\n self._embeddings[name] = vector.to(device, non_blocking=True).pin_memory()\n else:\n self._embeddings[name] = vector.to(device, non_blocking=True)\n\n def clear_embeddings(self, embedding_names: Optional[List[str]] = None):\n if embedding_names is None:\n self._embeddings = {}\n else:\n for name in embedding_names:\n if name in self._embeddings:\n del self._embeddings[name]\n\n def has_label(self, type) -> bool:\n return type in self.annotation_layers\n\n def add_metadata(self, key: str, value: typing.Any) -> None:\n self._metadata[key] = value\n\n def get_metadata(self, key: str) -> typing.Any:\n return self._metadata[key]\n\n def has_metadata(self, key: str) -> bool:\n return key in self._metadata\n\n def add_label(self, typename: str, value: str, score: float = 1.0):\n if typename not in self.annotation_layers:\n self.annotation_layers[typename] = [Label(self, value, score)]\n else:\n self.annotation_layers[typename].append(Label(self, value, score))\n\n return self\n\n def set_label(self, typename: str, value: str, score: float = 1.0):\n self.annotation_layers[typename] = [Label(self, value, score)]\n return self\n\n def remove_labels(self, typename: str):\n if typename in self.annotation_layers:\n del self.annotation_layers[typename]\n\n def get_label(self, label_type: Optional[str] = None, zero_tag_value=\"O\"):\n if len(self.get_labels(label_type)) == 0:\n return Label(self, zero_tag_value)\n return self.get_labels(label_type)[0]\n\n def get_labels(self, typename: Optional[str] = None):\n if typename is None:\n return self.labels\n\n return self.annotation_layers[typename] if typename in self.annotation_layers else []\n\n @property\n def labels(self) -> List[Label]:\n all_labels = []\n for key in self.annotation_layers:\n all_labels.extend(self.annotation_layers[key])\n return all_labels\n\n @property\n @abstractmethod\n def unlabeled_identifier(self):\n raise NotImplementedError\n\n def _printout_labels(self, main_label=None, add_score: bool = True):\n all_labels = []\n keys = [main_label] if main_label is not None else self.annotation_layers.keys()\n if add_score:\n for key in keys:\n all_labels.extend(\n [\n f\"{label.value} ({round(label.score, 4)})\"\n for label in self.get_labels(key)\n if label.data_point == self\n ]\n )\n labels = \"; \".join(all_labels)\n if labels != \"\":\n labels = flair._arrow + labels\n else:\n for key in keys:\n all_labels.extend([f\"{label.value}\" for label in self.get_labels(key) if label.data_point == self])\n labels = \"/\".join(all_labels)\n if labels != \"\":\n labels = \"/\" + labels\n return labels\n\n def __str__(self) -> str:\n return self.unlabeled_identifier + self._printout_labels()\n\n @property\n @abstractmethod\n def start_position(self) -> int:\n raise NotImplementedError\n\n @property\n @abstractmethod\n def end_position(self) -> int:\n raise NotImplementedError\n\n @property\n @abstractmethod\n def text(self):\n raise NotImplementedError\n\n @property\n def tag(self):\n return self.labels[0].value\n\n @property\n def score(self):\n return self.labels[0].score\n\n def __lt__(self, other):\n return self.start_position < other.start_position\n\n def __len__(self) -> int:\n raise NotImplementedError\n\n\nDT = typing.TypeVar(\"DT\", bound=DataPoint)\nDT2 = typing.TypeVar(\"DT2\", bound=DataPoint)\n\n\nclass _PartOfSentence(DataPoint, ABC):\n def __init__(self, sentence) -> None:\n super().__init__()\n self.sentence: Sentence = sentence\n\n def add_label(self, typename: str, value: str, score: float = 1.0):\n super().add_label(typename, value, score)\n self.sentence.annotation_layers.setdefault(typename, []).append(Label(self, value, score))\n\n def set_label(self, typename: str, value: str, score: float = 1.0):\n if len(self.annotation_layers.get(typename, [])) > 0:\n # First we remove any existing labels for this PartOfSentence in self.sentence\n self.sentence.annotation_layers[typename] = [\n label for label in self.sentence.annotation_layers.get(typename, []) if label.data_point != self\n ]\n self.sentence.annotation_layers.setdefault(typename, []).append(Label(self, value, score))\n super().set_label(typename, value, score)\n return self\n\n def remove_labels(self, typename: str):\n # labels also need to be deleted at Sentence object\n for label in self.get_labels(typename):\n self.sentence.annotation_layers[typename].remove(label)\n\n # delete labels at object itself\n super().remove_labels(typename)\n\n\nclass Token(_PartOfSentence):\n \"\"\"This class represents one word in a tokenized sentence.\n\n Each token may have any number of tags. It may also point to its head in a dependency tree.\n \"\"\"\n\n def __init__(\n self,\n text: str,\n head_id: Optional[int] = None,\n whitespace_after: int = 1,\n start_position: int = 0,\n sentence=None,\n ) -> None:\n super().__init__(sentence=sentence)\n\n self.form: str = text\n self._internal_index: Optional[int] = None\n self.head_id: Optional[int] = head_id\n self.whitespace_after: int = whitespace_after\n\n self._start_position = start_position\n\n self._embeddings: Dict = {}\n self.tags_proba_dist: Dict[str, List[Label]] = {}\n\n @property\n def idx(self) -> int:\n if self._internal_index is not None:\n return self._internal_index\n else:\n return -1\n\n @property\n def text(self) -> str:\n return self.form\n\n @property\n def unlabeled_identifier(self) -> str:\n return f'Token[{self.idx - 1}]: \"{self.text}\"'\n\n def add_tags_proba_dist(self, tag_type: str, tags: List[Label]):\n self.tags_proba_dist[tag_type] = tags\n\n def get_tags_proba_dist(self, tag_type: str) -> List[Label]:\n if tag_type in self.tags_proba_dist:\n return self.tags_proba_dist[tag_type]\n return []\n\n def get_head(self):\n return self.sentence.get_token(self.head_id)\n\n @property\n def start_position(self) -> int:\n return self._start_position\n\n @start_position.setter\n def start_position(self, value: int) -> None:\n self._start_position = value\n\n @property\n def end_position(self) -> int:\n return self.start_position + len(self.text)\n\n @property\n def embedding(self):\n return self.get_embedding()\n\n def __len__(self) -> int:\n return 1\n\n def __repr__(self) -> str:\n return self.__str__()\n\n def add_label(self, typename: str, value: str, score: float = 1.0):\n # The Token is a special _PartOfSentence in that it may be initialized without a Sentence.\n # therefore, labels get added only to the Sentence if it exists\n if self.sentence:\n super().add_label(typename=typename, value=value, score=score)\n else:\n DataPoint.add_label(self, typename=typename, value=value, score=score)\n\n def set_label(self, typename: str, value: str, score: float = 1.0):\n # The Token is a special _PartOfSentence in that it may be initialized without a Sentence.\n # Therefore, labels get set only to the Sentence if it exists\n if self.sentence:\n super().set_label(typename=typename, value=value, score=score)\n else:\n DataPoint.set_label(self, typename=typename, value=value, score=score)\n\n def to_dict(self, tag_type: Optional[str] = None):\n return {\n \"text\": self.text,\n \"start_pos\": self.start_position,\n \"end_pos\": self.end_position,\n \"labels\": [label.to_dict() for label in self.get_labels(tag_type)],\n }\n\n\nclass Span(_PartOfSentence):\n \"\"\"This class represents one textual span consisting of Tokens.\"\"\"\n\n def __new__(self, tokens: List[Token]):\n # check if the span already exists. If so, return it\n unlabeled_identifier = self._make_unlabeled_identifier(tokens)\n if unlabeled_identifier in tokens[0].sentence._known_spans:\n span = tokens[0].sentence._known_spans[unlabeled_identifier]\n return span\n\n # else make a new span\n else:\n span = super().__new__(self)\n span.initialized = False\n tokens[0].sentence._known_spans[unlabeled_identifier] = span\n return span\n\n def __init__(self, tokens: List[Token]) -> None:\n if not self.initialized:\n super().__init__(tokens[0].sentence)\n self.tokens = tokens\n self.initialized: bool = True\n\n @property\n def start_position(self) -> int:\n return self.tokens[0].start_position\n\n @property\n def end_position(self) -> int:\n return self.tokens[-1].end_position\n\n @property\n def text(self) -> str:\n return \"\".join([t.text + t.whitespace_after * \" \" for t in self.tokens]).strip()\n\n @staticmethod\n def _make_unlabeled_identifier(tokens: List[Token]):\n text = \"\".join([t.text + t.whitespace_after * \" \" for t in tokens]).strip()\n return f'Span[{tokens[0].idx - 1}:{tokens[-1].idx}]: \"{text}\"'\n\n @property\n def unlabeled_identifier(self) -> str:\n return self._make_unlabeled_identifier(self.tokens)\n\n def __repr__(self) -> str:\n return self.__str__()\n\n def __getitem__(self, idx: int) -> Token:\n return self.tokens[idx]\n\n def __iter__(self):\n return iter(self.tokens)\n\n def __len__(self) -> int:\n return len(self.tokens)\n\n @property\n def embedding(self):\n return self.get_embedding()\n\n def to_dict(self, tag_type: Optional[str] = None):\n return {\n \"text\": self.text,\n \"start_pos\": self.start_position,\n \"end_pos\": self.end_position,\n \"labels\": [label.to_dict() for label in self.get_labels(tag_type)],\n }\n\n\nclass Relation(_PartOfSentence):\n def __new__(self, first: Span, second: Span):\n # check if the relation already exists. If so, return it\n unlabeled_identifier = self._make_unlabeled_identifier(first, second)\n if unlabeled_identifier in first.sentence._known_spans:\n span = first.sentence._known_spans[unlabeled_identifier]\n return span\n\n # else make a new relation\n else:\n span = super().__new__(self)\n span.initialized = False\n first.sentence._known_spans[unlabeled_identifier] = span\n return span\n\n def __init__(self, first: Span, second: Span) -> None:\n if not self.initialized:\n super().__init__(sentence=first.sentence)\n self.first: Span = first\n self.second: Span = second\n self.initialized: bool = True\n\n def __repr__(self) -> str:\n return str(self)\n\n @property\n def tag(self):\n return self.labels[0].value\n\n @property\n def text(self):\n return f\"{self.first.text} -> {self.second.text}\"\n\n @staticmethod\n def _make_unlabeled_identifier(first, second):\n text = f\"{first.text} -> {second.text}\"\n return (\n f\"Relation\"\n f\"[{first.tokens[0].idx - 1}:{first.tokens[-1].idx}]\"\n f\"[{second.tokens[0].idx - 1}:{second.tokens[-1].idx}]\"\n f': \"{text}\"'\n )\n\n @property\n def unlabeled_identifier(self) -> str:\n return self._make_unlabeled_identifier(self.first, self.second)\n\n @property\n def start_position(self) -> int:\n return min(self.first.start_position, self.second.start_position)\n\n @property\n def end_position(self) -> int:\n return max(self.first.end_position, self.second.end_position)\n\n @property\n def embedding(self):\n pass\n\n def to_dict(self, tag_type: Optional[str] = None):\n return {\n \"from_text\": self.first.text,\n \"to_text\": self.second.text,\n \"from_idx\": self.first.tokens[0].idx - 1,\n \"to_idx\": self.second.tokens[0].idx - 1,\n \"labels\": [label.to_dict() for label in self.get_labels(tag_type)],\n }\n\n\nclass Sentence(DataPoint):\n \"\"\"A Sentence is a list of tokens and is used to represent a sentence or text fragment.\"\"\"\n\n def __init__(\n self,\n text: Union[str, List[str], List[Token]],\n use_tokenizer: Union[bool, Tokenizer] = True,\n language_code: Optional[str] = None,\n start_position: int = 0,\n ) -> None:\n \"\"\"Class to hold all metadata related to a text.\n\n Metadata can be tokens, labels, predictions, language code, etc.\n\n Args:\n text: original string (sentence), or a pre tokenized list of tokens.\n use_tokenizer: Specify a custom tokenizer to split the text into tokens. The Default is\n :class:`flair.tokenization.SegTokTokenizer`. If `use_tokenizer` is set to False,\n :class:`flair.tokenization.SpaceTokenizer` will be used instead. The tokenizer will be ignored,\n if `text` refers to pretokenized tokens.\n language_code: Language of the sentence. If not provided, `langdetect `_\n will be called when the language_code is accessed for the first time.\n start_position: Start char offset of the sentence in the superordinate document.\n \"\"\"\n super().__init__()\n\n self.tokens: List[Token] = []\n\n # private field for all known spans\n self._known_spans: Dict[str, _PartOfSentence] = {}\n\n self.language_code: Optional[str] = language_code\n\n self._start_position = start_position\n\n # the tokenizer used for this sentence\n if isinstance(use_tokenizer, Tokenizer):\n tokenizer = use_tokenizer\n\n elif isinstance(use_tokenizer, bool):\n tokenizer = SegtokTokenizer() if use_tokenizer else SpaceTokenizer()\n\n else:\n raise AssertionError(\"Unexpected type of parameter 'use_tokenizer'. Parameter should be bool or Tokenizer\")\n\n self.tokenized: Optional[str] = None\n\n # some sentences represent a document boundary (but most do not)\n self.is_document_boundary: bool = False\n\n # internal variables to denote position inside dataset\n self._previous_sentence: Optional[Sentence] = None\n self._has_context: bool = False\n self._next_sentence: Optional[Sentence] = None\n self._position_in_dataset: Optional[typing.Tuple[Dataset, int]] = None\n\n # if text is passed, instantiate sentence with tokens (words)\n if isinstance(text, str):\n text = Sentence._handle_problem_characters(text)\n words = tokenizer.tokenize(text)\n elif text and isinstance(text[0], Token):\n for t in text:\n self._add_token(t)\n self.tokens[-1].whitespace_after = 0\n return\n else:\n words = cast(List[str], text)\n text = \" \".join(words)\n\n # determine token positions and whitespace_after flag\n current_offset: int = 0\n previous_token: Optional[Token] = None\n for word in words:\n word_start_position: int = text.index(word, current_offset)\n delta_offset: int = word_start_position - current_offset\n\n token: Token = Token(text=word, start_position=word_start_position)\n self._add_token(token)\n\n if previous_token is not None:\n previous_token.whitespace_after = delta_offset\n\n current_offset = token.end_position\n previous_token = token\n\n # the last token has no whitespace after\n if len(self) > 0:\n self.tokens[-1].whitespace_after = 0\n\n # log a warning if the dataset is empty\n if text == \"\":\n log.warning(\"Warning: An empty Sentence was created! Are there empty strings in your dataset?\")\n\n @property\n def unlabeled_identifier(self):\n return f'Sentence[{len(self)}]: \"{self.text}\"'\n\n def get_relations(self, label_type: Optional[str] = None) -> List[Relation]:\n relations: List[Relation] = []\n for label in self.get_labels(label_type):\n if isinstance(label.data_point, Relation):\n relations.append(label.data_point)\n return relations\n\n def get_spans(self, label_type: Optional[str] = None) -> List[Span]:\n spans: List[Span] = []\n for potential_span in self._known_spans.values():\n if isinstance(potential_span, Span) and (label_type is None or potential_span.has_label(label_type)):\n spans.append(potential_span)\n return sorted(spans)\n\n def get_token(self, token_id: int) -> Optional[Token]:\n for token in self.tokens:\n if token.idx == token_id:\n return token\n return None\n\n def _add_token(self, token: Union[Token, str]):\n if isinstance(token, Token):\n assert token.sentence is None\n\n if isinstance(token, str):\n token = Token(token)\n token = cast(Token, token)\n\n # data with zero-width characters cannot be handled\n if token.text == \"\":\n return\n\n # set token idx and sentence\n token.sentence = self\n token._internal_index = len(self.tokens) + 1\n if token.start_position == 0 and token._internal_index > 1:\n token.start_position = len(self.to_original_text()) + self[-1].whitespace_after\n\n # append token to sentence\n self.tokens.append(token)\n\n # register token annotations on sentence\n for typename in token.annotation_layers:\n for label in token.get_labels(typename):\n if typename not in token.sentence.annotation_layers:\n token.sentence.annotation_layers[typename] = [Label(token, label.value, label.score)]\n else:\n token.sentence.annotation_layers[typename].append(Label(token, label.value, label.score))\n\n @property\n def embedding(self):\n return self.get_embedding()\n\n def to(self, device: str, pin_memory: bool = False):\n # move sentence embeddings to device\n super().to(device=device, pin_memory=pin_memory)\n\n # also move token embeddings to device\n for token in self:\n token.to(device, pin_memory)\n\n def clear_embeddings(self, embedding_names: Optional[List[str]] = None):\n super().clear_embeddings(embedding_names)\n\n # clear token embeddings\n for token in self:\n token.clear_embeddings(embedding_names)\n\n def left_context(self, context_length: int, respect_document_boundaries: bool = True) -> List[Token]:\n sentence = self\n left_context: List[Token] = []\n while len(left_context) < context_length:\n sentence = sentence.previous_sentence()\n if sentence is None:\n break\n\n if respect_document_boundaries and sentence.is_document_boundary:\n break\n\n left_context = sentence.tokens + left_context\n return left_context[-context_length:]\n\n def right_context(self, context_length: int, respect_document_boundaries: bool = True) -> List[Token]:\n sentence = self\n right_context: List[Token] = []\n while len(right_context) < context_length:\n sentence = sentence.next_sentence()\n if sentence is None:\n break\n if respect_document_boundaries and sentence.is_document_boundary:\n break\n\n right_context += sentence.tokens\n return right_context[:context_length]\n\n def __str__(self) -> str:\n return self.to_tagged_string()\n\n def to_tagged_string(self, main_label=None) -> str:\n already_printed = [self]\n\n output = super().__str__()\n\n label_append = []\n for label in self.get_labels(main_label):\n if label.data_point in already_printed:\n continue\n label_append.append(\n f'\"{label.data_point.text}\"{label.data_point._printout_labels(main_label=main_label, add_score=False)}'\n )\n already_printed.append(label.data_point)\n\n if len(label_append) > 0:\n output += f\"{flair._arrow}[\" + \", \".join(label_append) + \"]\"\n\n return output\n\n @property\n def text(self):\n return self.to_original_text()\n\n def to_tokenized_string(self) -> str:\n if self.tokenized is None:\n self.tokenized = \" \".join([t.text for t in self.tokens])\n\n return self.tokenized\n\n def to_plain_string(self):\n plain = \"\"\n for token in self.tokens:\n plain += token.text\n if token.whitespace_after > 0:\n plain += token.whitespace_after * \" \"\n return plain.rstrip()\n\n def infer_space_after(self):\n \"\"\"Heuristics in case you wish to infer whitespace_after values for tokenized text.\n\n This is useful for some old NLP tasks (such as CoNLL-03 and CoNLL-2000) that provide only tokenized data with\n no info of original whitespacing.\n :return:\n \"\"\"\n last_token = None\n quote_count: int = 0\n # infer whitespace after field\n\n for token in self.tokens:\n if token.text == '\"':\n quote_count += 1\n if quote_count % 2 != 0:\n token.whitespace_after = 0\n elif last_token is not None:\n last_token.whitespace_after = 0\n\n if last_token is not None:\n if token.text in [\".\", \":\", \",\", \";\", \")\", \"n't\", \"!\", \"?\"]:\n last_token.whitespace_after = 0\n\n if token.text.startswith(\"'\"):\n last_token.whitespace_after = 0\n\n if token.text in [\"(\"]:\n token.whitespace_after = 0\n\n last_token = token\n return self\n\n def to_original_text(self) -> str:\n # if sentence has no tokens, return empty string\n if len(self) == 0:\n return \"\"\n # otherwise, return concatenation of tokens with the correct offsets\n return (self[0].start_position - self.start_position) * \" \" + \"\".join(\n [t.text + t.whitespace_after * \" \" for t in self.tokens]\n ).strip()\n\n def to_dict(self, tag_type: Optional[str] = None):\n return {\n \"text\": self.to_original_text(),\n \"labels\": [label.to_dict() for label in self.get_labels(tag_type) if label.data_point is self],\n \"entities\": [span.to_dict(tag_type) for span in self.get_spans(tag_type)],\n \"relations\": [relation.to_dict(tag_type) for relation in self.get_relations(tag_type)],\n \"tokens\": [token.to_dict(tag_type) for token in self.tokens],\n }\n\n def get_span(self, start: int, stop: int):\n span_slice = slice(start, stop)\n return self[span_slice]\n\n @typing.overload\n def __getitem__(self, idx: int) -> Token:\n ...\n\n @typing.overload\n def __getitem__(self, s: slice) -> Span:\n ...\n\n def __getitem__(self, subscript):\n if isinstance(subscript, slice):\n return Span(self.tokens[subscript])\n else:\n return self.tokens[subscript]\n\n def __iter__(self):\n return iter(self.tokens)\n\n def __len__(self) -> int:\n return len(self.tokens)\n\n def __repr__(self) -> str:\n return self.__str__()\n\n @property\n def start_position(self) -> int:\n return self._start_position\n\n @start_position.setter\n def start_position(self, value: int) -> None:\n self._start_position = value\n\n @property\n def end_position(self) -> int:\n # The sentence's start position is not propagated to its tokens.\n # Therefore, we need to add the sentence's start position to its last token's end position, including whitespaces.\n return self.start_position + self[-1].end_position + self[-1].whitespace_after\n\n def get_language_code(self) -> str:\n if self.language_code is None:\n import langdetect\n\n try:\n self.language_code = langdetect.detect(self.to_plain_string())\n except Exception:\n self.language_code = \"en\"\n\n return self.language_code\n\n @staticmethod\n def _handle_problem_characters(text: str) -> str:\n text = Sentence.__remove_zero_width_characters(text)\n text = Sentence.__restore_windows_1252_characters(text)\n return text\n\n @staticmethod\n def __remove_zero_width_characters(text: str) -> str:\n text = text.replace(\"\\u200c\", \"\")\n text = text.replace(\"\\u200b\", \"\")\n text = text.replace(\"\\ufe0f\", \"\")\n text = text.replace(\"\\ufeff\", \"\")\n return text\n\n @staticmethod\n def __restore_windows_1252_characters(text: str) -> str:\n def to_windows_1252(match):\n try:\n return bytes([ord(match.group(0))]).decode(\"windows-1252\")\n except UnicodeDecodeError:\n # No character at the corresponding code point: remove it\n return \"\"\n\n return re.sub(r\"[\\u0080-\\u0099]\", to_windows_1252, text)\n\n def next_sentence(self):\n \"\"\"Get the next sentence in the document.\n\n This only works if context is set through dataloader or elsewhere\n :return: next Sentence in document if set, otherwise None\n \"\"\"\n if self._next_sentence is not None:\n return self._next_sentence\n\n if self._position_in_dataset is not None:\n dataset = self._position_in_dataset[0]\n index = self._position_in_dataset[1] + 1\n if index < len(dataset):\n return dataset[index]\n\n return None\n\n def previous_sentence(self):\n \"\"\"Get the previous sentence in the document.\n\n works only if context is set through dataloader or elsewhere\n :return: previous Sentence in document if set, otherwise None\n \"\"\"\n if self._previous_sentence is not None:\n return self._previous_sentence\n\n if self._position_in_dataset is not None:\n dataset = self._position_in_dataset[0]\n index = self._position_in_dataset[1] - 1\n if index >= 0:\n return dataset[index]\n\n return None\n\n def is_context_set(self) -> bool:\n \"\"\"Determines if this sentence has a context of sentences before or after set.\n\n Return True or False depending on whether context is set (for instance in dataloader or elsewhere)\n :return: True if context is set, else False\n \"\"\"\n return (\n self._has_context\n or self._previous_sentence is not None\n or self._next_sentence is not None\n or self._position_in_dataset is not None\n )\n\n def copy_context_from_sentence(self, sentence: \"Sentence\") -> None:\n self._previous_sentence = sentence._previous_sentence\n self._next_sentence = sentence._next_sentence\n self._position_in_dataset = sentence._position_in_dataset\n\n @classmethod\n def set_context_for_sentences(cls, sentences: List[\"Sentence\"]) -> None:\n previous_sentence = None\n for sentence in sentences:\n if sentence.is_context_set():\n continue\n sentence._previous_sentence = previous_sentence\n sentence._next_sentence = None\n sentence._has_context = True\n if previous_sentence is not None:\n previous_sentence._next_sentence = sentence\n previous_sentence = sentence\n\n def get_labels(self, label_type: Optional[str] = None):\n # if no label if specified, return all labels\n if label_type is None:\n return sorted(self.labels)\n\n # if the label type exists in the Sentence, return it\n if label_type in self.annotation_layers:\n return sorted(self.annotation_layers[label_type])\n\n # return empty list if none of the above\n return []\n\n def remove_labels(self, typename: str):\n # labels also need to be deleted at all tokens\n for token in self:\n token.remove_labels(typename)\n\n # labels also need to be deleted at all known spans\n for span in self._known_spans.values():\n span.remove_labels(typename)\n\n # remove spans without labels\n self._known_spans = {k: v for k, v in self._known_spans.items() if len(v.labels) > 0}\n\n # delete labels at object itself\n super().remove_labels(typename)\n\n\nclass DataPair(DataPoint, typing.Generic[DT, DT2]):\n def __init__(self, first: DT, second: DT2) -> None:\n super().__init__()\n self.first = first\n self.second = second\n\n def to(self, device: str, pin_memory: bool = False):\n self.first.to(device, pin_memory)\n self.second.to(device, pin_memory)\n\n def clear_embeddings(self, embedding_names: Optional[List[str]] = None):\n self.first.clear_embeddings(embedding_names)\n self.second.clear_embeddings(embedding_names)\n\n @property\n def embedding(self):\n return torch.cat([self.first.embedding, self.second.embedding])\n\n def __len__(self) -> int:\n return len(self.first) + len(self.second)\n\n @property\n def unlabeled_identifier(self):\n return f\"DataPair: '{self.first.unlabeled_identifier}' + '{self.second.unlabeled_identifier}'\"\n\n @property\n def start_position(self) -> int:\n return self.first.start_position\n\n @property\n def end_position(self) -> int:\n return self.first.end_position\n\n @property\n def text(self):\n return self.first.text + \" || \" + self.second.text\n\n\nTextPair = DataPair[Sentence, Sentence]\n\n\nclass Image(DataPoint):\n def __init__(self, data=None, imageURL=None) -> None:\n super().__init__()\n\n self.data = data\n self._embeddings: Dict = {}\n self.imageURL = imageURL\n\n @property\n def embedding(self):\n return self.get_embedding()\n\n def __str__(self) -> str:\n image_repr = self.data.size() if self.data else \"\"\n image_url = self.imageURL if self.imageURL else \"\"\n\n return f\"Image: {image_repr} {image_url}\"\n\n @property\n def start_position(self) -> int:\n raise NotImplementedError\n\n @property\n def end_position(self) -> int:\n raise NotImplementedError\n\n @property\n def text(self) -> str:\n raise NotImplementedError\n\n @property\n def unlabeled_identifier(self) -> str:\n raise NotImplementedError\n\n\nclass Corpus(typing.Generic[T_co]):\n def __init__(\n self,\n train: Optional[Dataset[T_co]] = None,\n dev: Optional[Dataset[T_co]] = None,\n test: Optional[Dataset[T_co]] = None,\n name: str = \"corpus\",\n sample_missing_splits: Union[bool, str] = True,\n ) -> None:\n # set name\n self.name: str = name\n\n # abort if no data is provided\n if not train and not dev and not test:\n raise RuntimeError(\"No data provided when initializing corpus object.\")\n\n # sample test data from train if none is provided\n if test is None and sample_missing_splits and train and sample_missing_splits != \"only_dev\":\n test_portion = 0.1\n train_length = _len_dataset(train)\n test_size: int = round(train_length * test_portion)\n test, train = randomly_split_into_two_datasets(train, test_size)\n log.warning(\n \"No test split found. Using %.0f%% (i.e. %d samples) of the train split as test data\",\n test_portion,\n test_size,\n )\n\n # sample dev data from train if none is provided\n if dev is None and sample_missing_splits and train and sample_missing_splits != \"only_test\":\n dev_portion = 0.1\n train_length = _len_dataset(train)\n dev_size: int = round(train_length * dev_portion)\n dev, train = randomly_split_into_two_datasets(train, dev_size)\n log.warning(\n \"No dev split found. Using %.0f%% (i.e. %d samples) of the train split as dev data\",\n dev_portion,\n dev_size,\n )\n\n # set train dev and test data\n self._train: Optional[Dataset[T_co]] = train\n self._test: Optional[Dataset[T_co]] = test\n self._dev: Optional[Dataset[T_co]] = dev\n\n @property\n def train(self) -> Optional[Dataset[T_co]]:\n return self._train\n\n @property\n def dev(self) -> Optional[Dataset[T_co]]:\n return self._dev\n\n @property\n def test(self) -> Optional[Dataset[T_co]]:\n return self._test\n\n def downsample(\n self,\n percentage: float = 0.1,\n downsample_train=True,\n downsample_dev=True,\n downsample_test=True,\n ):\n if downsample_train and self._train is not None:\n self._train = self._downsample_to_proportion(self._train, percentage)\n\n if downsample_dev and self._dev is not None:\n self._dev = self._downsample_to_proportion(self._dev, percentage)\n\n if downsample_test and self._test is not None:\n self._test = self._downsample_to_proportion(self._test, percentage)\n\n return self\n\n def filter_empty_sentences(self):\n log.info(\"Filtering empty sentences\")\n if self._train is not None:\n self._train = Corpus._filter_empty_sentences(self._train)\n if self._test is not None:\n self._test = Corpus._filter_empty_sentences(self._test)\n if self._dev is not None:\n self._dev = Corpus._filter_empty_sentences(self._dev)\n log.info(self)\n\n def filter_long_sentences(self, max_charlength: int):\n log.info(\"Filtering long sentences\")\n if self._train is not None:\n self._train = Corpus._filter_long_sentences(self._train, max_charlength)\n if self._test is not None:\n self._test = Corpus._filter_long_sentences(self._test, max_charlength)\n if self._dev is not None:\n self._dev = Corpus._filter_long_sentences(self._dev, max_charlength)\n log.info(self)\n\n @staticmethod\n def _filter_long_sentences(dataset, max_charlength: int) -> Dataset:\n # find out empty sentence indices\n empty_sentence_indices = []\n non_empty_sentence_indices = []\n\n for index, sentence in Tqdm.tqdm(enumerate(_iter_dataset(dataset))):\n if len(sentence.to_plain_string()) > max_charlength:\n empty_sentence_indices.append(index)\n else:\n non_empty_sentence_indices.append(index)\n\n # create subset of non-empty sentence indices\n subset = Subset(dataset, non_empty_sentence_indices)\n\n return subset\n\n @staticmethod\n def _filter_empty_sentences(dataset) -> Dataset:\n # find out empty sentence indices\n empty_sentence_indices = []\n non_empty_sentence_indices = []\n\n for index, sentence in enumerate(_iter_dataset(dataset)):\n if len(sentence) == 0:\n empty_sentence_indices.append(index)\n else:\n non_empty_sentence_indices.append(index)\n\n # create subset of non-empty sentence indices\n subset = Subset(dataset, non_empty_sentence_indices)\n\n return subset\n\n def make_vocab_dictionary(self, max_tokens=-1, min_freq=1) -> Dictionary:\n \"\"\"Creates a dictionary of all tokens contained in the corpus.\n\n By defining `max_tokens` you can set the maximum number of tokens that should be contained in the dictionary.\n If there are more than `max_tokens` tokens in the corpus, the most frequent tokens are added first.\n If `min_freq` is set to a value greater than 1 only tokens occurring more than `min_freq` times are considered\n to be added to the dictionary.\n\n Args:\n max_tokens: the maximum number of tokens that should be added to the dictionary (-1 = take all tokens)\n min_freq: a token needs to occur at least `min_freq` times to be added to the dictionary (-1 = there is no limitation)\n\n Returns: dictionary of tokens\n \"\"\"\n tokens = self._get_most_common_tokens(max_tokens, min_freq)\n\n vocab_dictionary: Dictionary = Dictionary()\n for token in tokens:\n vocab_dictionary.add_item(token)\n\n return vocab_dictionary\n\n def _get_most_common_tokens(self, max_tokens, min_freq) -> List[str]:\n tokens_and_frequencies = Counter(self._get_all_tokens())\n\n tokens: List[str] = []\n for token, freq in tokens_and_frequencies.most_common():\n if (min_freq != -1 and freq < min_freq) or (max_tokens != -1 and len(tokens) == max_tokens):\n break\n tokens.append(token)\n return tokens\n\n def _get_all_tokens(self) -> List[str]:\n assert self.train\n tokens = [s.tokens for s in _iter_dataset(self.train)]\n tokens = [token for sublist in tokens for token in sublist]\n return [t.text for t in tokens]\n\n @staticmethod\n def _downsample_to_proportion(dataset: Dataset, proportion: float):\n sampled_size: int = round(_len_dataset(dataset) * proportion)\n splits = randomly_split_into_two_datasets(dataset, sampled_size)\n return splits[0]\n\n def obtain_statistics(self, label_type: Optional[str] = None, pretty_print: bool = True) -> Union[dict, str]:\n \"\"\"Print statistics about the class distribution and sentence sizes.\n\n only labels of sentences are taken into account\n \"\"\"\n json_data = {\n \"TRAIN\": self._obtain_statistics_for(self.train, \"TRAIN\", label_type),\n \"TEST\": self._obtain_statistics_for(self.test, \"TEST\", label_type),\n \"DEV\": self._obtain_statistics_for(self.dev, \"DEV\", label_type),\n }\n if pretty_print:\n import json\n\n return json.dumps(json_data, indent=4)\n return json_data\n\n @staticmethod\n def _obtain_statistics_for(sentences, name, tag_type) -> dict:\n if len(sentences) == 0:\n return {}\n\n classes_to_count = Corpus._count_sentence_labels(sentences)\n tags_to_count = Corpus._count_token_labels(sentences, tag_type)\n tokens_per_sentence = Corpus._get_tokens_per_sentence(sentences)\n\n label_size_dict = {}\n for label, c in classes_to_count.items():\n label_size_dict[label] = c\n\n tag_size_dict = {}\n for tag, c in tags_to_count.items():\n tag_size_dict[tag] = c\n\n return {\n \"dataset\": name,\n \"total_number_of_documents\": len(sentences),\n \"number_of_documents_per_class\": label_size_dict,\n \"number_of_tokens_per_tag\": tag_size_dict,\n \"number_of_tokens\": {\n \"total\": sum(tokens_per_sentence),\n \"min\": min(tokens_per_sentence),\n \"max\": max(tokens_per_sentence),\n \"avg\": sum(tokens_per_sentence) / len(sentences),\n },\n }\n\n @staticmethod\n def _get_tokens_per_sentence(sentences):\n return [len(x.tokens) for x in sentences]\n\n @staticmethod\n def _count_sentence_labels(sentences):\n label_count = defaultdict(lambda: 0)\n for sent in sentences:\n for label in sent.labels:\n label_count[label.value] += 1\n return label_count\n\n @staticmethod\n def _count_token_labels(sentences, label_type):\n label_count = defaultdict(lambda: 0)\n for sent in sentences:\n for token in sent.tokens:\n if label_type in token.annotation_layers:\n label = token.get_label(label_type)\n label_count[label.value] += 1\n return label_count\n\n def __str__(self) -> str:\n return \"Corpus: %d train + %d dev + %d test sentences\" % (\n _len_dataset(self.train) if self.train else 0,\n _len_dataset(self.dev) if self.dev else 0,\n _len_dataset(self.test) if self.test else 0,\n )\n\n def make_label_dictionary(\n self, label_type: str, min_count: int = -1, add_unk: bool = False, add_dev_test: bool = False\n ) -> Dictionary:\n \"\"\"Creates a dictionary of all labels assigned to the sentences in the corpus.\n\n :return: dictionary of labels\n \"\"\"\n if min_count > 0 and not add_unk:\n add_unk = True\n log.info(\"Adding -token to dictionary since min_count is set.\")\n\n label_dictionary: Dictionary = Dictionary(add_unk=add_unk)\n label_dictionary.span_labels = False\n\n assert self.train\n datasets = [self.train]\n\n if add_dev_test and self.dev is not None:\n datasets.append(self.dev)\n\n if add_dev_test and self.test is not None:\n datasets.append(self.test)\n\n data: ConcatDataset = ConcatDataset(datasets)\n\n log.info(\"Computing label dictionary. Progress:\")\n\n sentence_label_type_counter: typing.Counter[str] = Counter()\n label_value_counter: typing.Counter[str] = Counter()\n all_sentence_labels: List[str] = []\n\n # first, determine the datapoint type by going through dataset until first label is found\n datapoint_type = None\n for sentence in Tqdm.tqdm(_iter_dataset(data)):\n labels = sentence.get_labels(label_type)\n for label in labels:\n datapoint_type = type(label.data_point)\n if datapoint_type:\n break\n\n if datapoint_type == Span:\n label_dictionary.span_labels = True\n\n for sentence in Tqdm.tqdm(_iter_dataset(data)):\n # count all label types per sentence\n sentence_label_type_counter.update(sentence.annotation_layers.keys())\n\n # go through all labels of label_type and count values\n labels = sentence.get_labels(label_type)\n label_value_counter.update(label.value for label in labels if label.value not in all_sentence_labels)\n\n # special handling for Token-level annotations. Add all untagged as 'O' label\n if datapoint_type == Token and len(sentence) > len(labels):\n label_value_counter[\"O\"] += len(sentence) - len(labels)\n\n if not label_dictionary.multi_label and len(labels) > 1:\n label_dictionary.multi_label = True\n\n # if an unk threshold is set, UNK all label values below this threshold\n total_count = 0\n unked_count = 0\n for label, count in label_value_counter.most_common():\n if count >= min_count:\n label_dictionary.add_item(label)\n total_count += count\n else:\n unked_count += count\n\n if len(label_dictionary.idx2item) == 0 or (\n len(label_dictionary.idx2item) == 1 and \"\" in label_dictionary.get_items()\n ):\n log.error(f\"ERROR: You specified label_type='{label_type}' which is not in this dataset!\")\n contained_labels = \", \".join(\n [f\"'{label[0]}' (in {label[1]} sentences)\" for label in sentence_label_type_counter.most_common()]\n )\n log.error(f\"ERROR: The corpus contains the following label types: {contained_labels}\")\n raise Exception\n\n log.info(\n f\"Dictionary created for label '{label_type}' with {len(label_dictionary)} \"\n f\"values: {', '.join([label[0] + f' (seen {label[1]} times)' for label in label_value_counter.most_common(20)])}\"\n )\n\n if unked_count > 0:\n log.info(f\" - at UNK threshold {min_count}, {unked_count} instances are UNK'ed and {total_count} remain\")\n\n return label_dictionary\n\n def add_label_noise(\n self,\n label_type: str,\n labels: List[str],\n noise_share: float = 0.2,\n split: str = \"train\",\n noise_transition_matrix: Optional[Dict[str, List[float]]] = None,\n ):\n \"\"\"Generates uniform label noise distribution in the chosen dataset split.\n\n Args:\n label_type: the type of labels for which the noise should be simulated.\n labels: an array with unique labels of said type (retrievable from label dictionary).\n noise_share: the desired share of noise in the train split.\n split: in which dataset split the noise is to be simulated.\n noise_transition_matrix: provides pre-defined probabilities for label flipping based on the initial\n label value (relevant for class-dependent label noise simulation).\n \"\"\"\n import numpy as np\n\n if split == \"train\":\n assert self.train\n datasets = [self.train]\n elif split == \"dev\":\n assert self.dev\n datasets = [self.dev]\n elif split == \"test\":\n assert self.test\n datasets = [self.test]\n else:\n raise ValueError(\"split must be either train, dev or test.\")\n\n data: ConcatDataset = ConcatDataset(datasets)\n\n corrupted_count = 0\n total_label_count = 0\n\n if noise_transition_matrix:\n ntm_labels = noise_transition_matrix.keys()\n\n if set(ntm_labels) != set(labels):\n raise AssertionError(\n \"Label values in the noise transition matrix have to coincide with label values in the dataset\"\n )\n\n log.info(\"Generating noisy labels. Progress:\")\n\n for data_point in Tqdm.tqdm(_iter_dataset(data)):\n for label in data_point.get_labels(label_type):\n total_label_count += 1\n orig_label = label.value\n # sample randomly from a label distribution according to the probabilities defined by the noise transition matrix\n new_label = np.random.default_rng().choice(\n a=list(ntm_labels),\n p=noise_transition_matrix[orig_label],\n )\n # replace the old label with the new one\n label.data_point.set_label(label_type, new_label)\n # keep track of the old (clean) label using another label type category\n label.data_point.add_label(label_type + \"_clean\", orig_label)\n # keep track of how many labels in total are flipped\n if new_label != orig_label:\n corrupted_count += 1\n\n else:\n if noise_share < 0 or noise_share > 1:\n raise ValueError(\"noise_share must be between 0 and 1.\")\n\n orig_label_p = 1 - noise_share\n other_label_p = noise_share / (len(labels) - 1)\n\n log.info(\"Generating noisy labels. Progress:\")\n\n for data_point in Tqdm.tqdm(_iter_dataset(data)):\n for label in data_point.get_labels(label_type):\n total_label_count += 1\n orig_label = label.value\n prob_dist = [other_label_p] * len(labels)\n prob_dist[labels.index(orig_label)] = orig_label_p\n # sample randomly from a label distribution according to the probabilities defined by the desired noise share\n new_label = np.random.default_rng().choice(a=labels, p=prob_dist)\n # replace the old label with the new one\n label.data_point.set_label(label_type, new_label)\n # keep track of the old (clean) label using another label type category\n label.data_point.add_label(label_type + \"_clean\", orig_label)\n # keep track of how many labels in total are flipped\n if new_label != orig_label:\n corrupted_count += 1\n\n log.info(\n f\"Total labels corrupted: {corrupted_count}. Resulting noise share: {round((corrupted_count / total_label_count) * 100, 2)}%.\"\n )\n\n def get_label_distribution(self):\n class_to_count = defaultdict(lambda: 0)\n for sent in self.train:\n for label in sent.labels:\n class_to_count[label.value] += 1\n return class_to_count\n\n def get_all_sentences(self) -> ConcatDataset:\n parts = []\n if self.train:\n parts.append(self.train)\n if self.dev:\n parts.append(self.dev)\n if self.test:\n parts.append(self.test)\n return ConcatDataset(parts)\n\n @deprecated(version=\"0.8\", reason=\"Use 'make_label_dictionary' instead.\")\n def make_tag_dictionary(self, tag_type: str) -> Dictionary:\n \"\"\"Create a tag dictionary of a given label type.\n\n Args:\n tag_type: the label type to gather the tag labels\n\n Returns: A Dictionary containing the labeled tags, including \"O\" and \"\" and \"\"\n\n \"\"\"\n tag_dictionary: Dictionary = Dictionary(add_unk=False)\n tag_dictionary.add_item(\"O\")\n for sentence in _iter_dataset(self.get_all_sentences()):\n for token in sentence.tokens:\n tag_dictionary.add_item(token.get_label(tag_type).value)\n tag_dictionary.add_item(\"\")\n tag_dictionary.add_item(\"\")\n return tag_dictionary\n\n\nclass MultiCorpus(Corpus):\n def __init__(\n self,\n corpora: List[Corpus],\n task_ids: Optional[List[str]] = None,\n name: str = \"multicorpus\",\n **corpusargs,\n ) -> None:\n self.corpora: List[Corpus] = corpora\n\n ids = task_ids if task_ids else [f\"Task_{i}\" for i in range(len(corpora))]\n\n train_parts = []\n dev_parts = []\n test_parts = []\n for corpus in self.corpora:\n if corpus.train:\n train_parts.append(corpus.train)\n if corpus.dev:\n dev_parts.append(corpus.dev)\n if corpus.test:\n test_parts.append(corpus.test)\n\n super().__init__(\n ConcatFlairDataset(train_parts, ids) if len(train_parts) > 0 else None,\n ConcatFlairDataset(dev_parts, ids) if len(dev_parts) > 0 else None,\n ConcatFlairDataset(test_parts, ids) if len(test_parts) > 0 else None,\n name=name,\n **corpusargs,\n )\n\n def __str__(self) -> str:\n output = (\n f\"MultiCorpus: \" # type: ignore[arg-type]\n f\"{len(self.train) if self.train else 0} train + \"\n f\"{len(self.dev) if self.dev else 0} dev + \"\n f\"{len(self.test) if self.test else 0} test sentences\\n - \"\n )\n output += \"\\n - \".join([f\"{type(corpus).__name__} {corpus!s} - {corpus.name}\" for corpus in self.corpora])\n return output\n\n\nclass FlairDataset(Dataset):\n @abstractmethod\n def is_in_memory(self) -> bool:\n pass\n\n\nclass ConcatFlairDataset(Dataset):\n r\"\"\"Dataset as a concatenation of multiple datasets.\n\n This class is useful to assemble different existing datasets.\n\n Args:\n datasets (sequence): List of datasets to be concatenated\n \"\"\"\n\n datasets: List[Dataset]\n cumulative_sizes: List[int]\n\n @staticmethod\n def cumsum(sequence):\n r, s = [], 0\n for e in sequence:\n length_of_e = len(e)\n r.append(length_of_e + s)\n s += length_of_e\n return r\n\n def __init__(self, datasets: Iterable[Dataset], ids: Iterable[str]) -> None:\n super().__init__()\n self.datasets = list(datasets)\n self.ids = list(ids)\n assert len(self.datasets) > 0, \"datasets should not be an empty iterable\"\n for d in self.datasets:\n assert not isinstance(d, IterableDataset), \"ConcatSentenceDataset does not support IterableDataset\"\n self.cumulative_sizes = self.cumsum(self.datasets)\n\n def __len__(self) -> int:\n return self.cumulative_sizes[-1]\n\n def __getitem__(self, idx):\n if idx < 0:\n if -idx > len(self):\n raise ValueError(\"absolute value of index should not exceed dataset length\")\n idx = len(self) + idx\n dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)\n sample_idx = idx if dataset_idx == 0 else idx - self.cumulative_sizes[dataset_idx - 1]\n sentence = self.datasets[dataset_idx][sample_idx]\n sentence.set_label(\"multitask_id\", self.ids[dataset_idx])\n return sentence\n\n @property\n def cummulative_sizes(self):\n return self.cumulative_sizes\n\n\ndef iob2(tags):\n \"\"\"Converts the tags to the IOB2 format.\n\n Check that tags have a valid IOB format.\n Tags in IOB1 format are converted to IOB2.\n \"\"\"\n for i, tag in enumerate(tags):\n if tag.value == \"O\":\n continue\n split = tag.value.split(\"-\")\n if len(split) != 2 or split[0] not in [\"I\", \"B\"]:\n return False\n if split[0] == \"B\":\n continue\n elif i == 0 or tags[i - 1].value == \"O\": # conversion IOB1 to IOB2\n tags[i].value = \"B\" + tag.value[1:]\n elif tags[i - 1].value[1:] == tag.value[1:]:\n continue\n else: # conversion IOB1 to IOB2\n tags[i].value = \"B\" + tag.value[1:]\n return True\n\n\ndef randomly_split_into_two_datasets(dataset, length_of_first):\n import random\n\n indices = list(range(len(dataset)))\n random.shuffle(indices)\n\n first_dataset = indices[:length_of_first]\n second_dataset = indices[length_of_first:]\n first_dataset.sort()\n second_dataset.sort()\n\n return Subset(dataset, first_dataset), Subset(dataset, second_dataset)\n\n\ndef get_spans_from_bio(bioes_tags: List[str], bioes_scores=None) -> List[typing.Tuple[List[int], float, str]]:\n # add a dummy \"O\" to close final prediction\n bioes_tags.append(\"O\")\n # return complex list\n found_spans = []\n # internal variables\n current_tag_weights: Dict[str, float] = {}\n previous_tag = \"O-\"\n current_span: List[int] = []\n current_span_scores: List[float] = []\n for idx, bioes_tag in enumerate(bioes_tags):\n # non-set tags are OUT tags\n if bioes_tag == \"\" or bioes_tag == \"O\" or bioes_tag == \"_\":\n bioes_tag = \"O-\"\n\n # anything that is not OUT is IN\n in_span = bioes_tag != \"O-\"\n\n # does this prediction start a new span?\n starts_new_span = False\n\n if bioes_tag[:2] in {\"B-\", \"S-\"} or (\n in_span and previous_tag[2:] != bioes_tag[2:] and (bioes_tag[:2] == \"I-\" or previous_tag[2:] == \"S-\")\n ):\n # B- and S- always start new spans\n # if the predicted class changes, I- starts a new span\n # if the predicted class changes and S- was previous tag, start a new span\n starts_new_span = True\n\n # if an existing span is ended (either by reaching O or starting a new span)\n if (starts_new_span or not in_span) and len(current_span) > 0:\n # determine score and value\n span_score = sum(current_span_scores) / len(current_span_scores)\n span_value = max(current_tag_weights.keys(), key=current_tag_weights.__getitem__)\n\n # append to result list\n found_spans.append((current_span, span_score, span_value))\n\n # reset for-loop variables for new span\n current_span = []\n current_span_scores = []\n current_tag_weights = {}\n\n if in_span:\n current_span.append(idx)\n current_span_scores.append(bioes_scores[idx] if bioes_scores else 1.0)\n weight = 1.1 if starts_new_span else 1.0\n current_tag_weights[bioes_tag[2:]] = current_tag_weights.setdefault(bioes_tag[2:], 0.0) + weight\n\n # remember previous tag\n previous_tag = bioes_tag\n\n return found_spans\n","repo_name":"flairNLP/flair","sub_path":"flair/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":67168,"program_lang":"python","lang":"en","doc_type":"code","stars":13236,"dataset":"github-code","pt":"85"} +{"seq_id":"38238139801","text":"\"\"\"\nNamespace that defines fields common to all blocks used in the LMS\n\"\"\"\n\n#from django.utils.translation import ugettext_noop as _\nfrom lazy import lazy\n\nfrom xblock.fields import Boolean, Scope, String, XBlockMixin, Dict\nfrom xblock.validation import ValidationMessage\nfrom xmodule.modulestore.inheritance import UserPartitionList\nfrom xmodule.partitions.partitions import NoSuchUserPartitionError, NoSuchUserPartitionGroupError\n\n# Please do not remove, this is a workaround for Django 1.8.\n# more information can be found here: https://openedx.atlassian.net/browse/PLAT-902\n_ = lambda text: text\n\n\nclass GroupAccessDict(Dict):\n \"\"\"Special Dict class for serializing the group_access field\"\"\"\n def from_json(self, access_dict):\n if access_dict is not None:\n return {int(k): access_dict[k] for k in access_dict}\n\n def to_json(self, access_dict):\n if access_dict is not None:\n return {unicode(k): access_dict[k] for k in access_dict}\n\n\nclass LmsBlockMixin(XBlockMixin):\n \"\"\"\n Mixin that defines fields common to all blocks used in the LMS\n \"\"\"\n hide_from_toc = Boolean(\n help=_(\"Whether to display this module in the table of contents\"),\n default=False,\n scope=Scope.settings\n )\n format = String(\n # Translators: \"TOC\" stands for \"Table of Contents\"\n help=_(\"What format this module is in (used for deciding which \"\n \"grader to apply, and what to show in the TOC)\"),\n scope=Scope.settings,\n )\n chrome = String(\n display_name=_(\"Courseware Chrome\"),\n # Translators: DO NOT translate the words in quotes here, they are\n # specific words for the acceptable values.\n help=_(\"Enter the chrome, or navigation tools, to use for the XBlock in the LMS. Valid values are: \\n\"\n \"\\\"chromeless\\\" -- to not use tabs or the accordion; \\n\"\n \"\\\"tabs\\\" -- to use tabs only; \\n\"\n \"\\\"accordion\\\" -- to use the accordion only; or \\n\"\n \"\\\"tabs,accordion\\\" -- to use tabs and the accordion.\"),\n scope=Scope.settings,\n default=None,\n )\n default_tab = String(\n display_name=_(\"Default Tab\"),\n help=_(\"Enter the tab that is selected in the XBlock. If not set, the Courseware tab is selected.\"),\n scope=Scope.settings,\n default=None,\n )\n source_file = String(\n display_name=_(\"LaTeX Source File Name\"),\n help=_(\"Enter the source file name for LaTeX.\"),\n scope=Scope.settings,\n deprecated=True\n )\n visible_to_staff_only = Boolean(\n help=_(\"If true, can be seen only by course staff, regardless of start date.\"),\n default=False,\n scope=Scope.settings,\n )\n group_access = GroupAccessDict(\n help=_(\n \"A dictionary that maps which groups can be shown this block. The keys \"\n \"are group configuration ids and the values are a list of group IDs. \"\n \"If there is no key for a group configuration or if the set of group IDs \"\n \"is empty then the block is considered visible to all. Note that this \"\n \"field is ignored if the block is visible_to_staff_only.\"\n ),\n default={},\n scope=Scope.settings,\n )\n\n @lazy\n def merged_group_access(self):\n \"\"\"\n This computes access to a block's group_access rules in the context of its position\n within the courseware structure, in the form of a lazily-computed attribute.\n Each block's group_access rule is merged recursively with its parent's, guaranteeing\n that any rule in a parent block will be enforced on descendants, even if a descendant\n also defined its own access rules. The return value is always a dict, with the same\n structure as that of the group_access field.\n\n When merging access rules results in a case where all groups are denied access in a\n user partition (which effectively denies access to that block for all students),\n the special value False will be returned for that user partition key.\n \"\"\"\n parent = self.get_parent()\n if not parent:\n return self.group_access or {}\n\n merged_access = parent.merged_group_access.copy()\n if self.group_access is not None:\n for partition_id, group_ids in self.group_access.items():\n if group_ids: # skip if the \"local\" group_access for this partition is None or empty.\n if partition_id in merged_access:\n if merged_access[partition_id] is False:\n # special case - means somewhere up the hierarchy, merged access rules have eliminated\n # all group_ids from this partition, so there's no possible intersection.\n continue\n # otherwise, if the parent defines group access rules for this partition,\n # intersect with the local ones.\n merged_access[partition_id] = list(\n set(merged_access[partition_id]).intersection(group_ids)\n ) or False\n else:\n # add the group access rules for this partition to the merged set of rules.\n merged_access[partition_id] = group_ids\n return merged_access\n\n # Specified here so we can see what the value set at the course-level is.\n user_partitions = UserPartitionList(\n help=_(\"The list of group configurations for partitioning students in content experiments.\"),\n default=[],\n scope=Scope.settings\n )\n\n def _get_user_partition(self, user_partition_id):\n \"\"\"\n Returns the user partition with the specified id. Raises\n `NoSuchUserPartitionError` if the lookup fails.\n \"\"\"\n for user_partition in self.user_partitions:\n if user_partition.id == user_partition_id:\n return user_partition\n\n raise NoSuchUserPartitionError(\"could not find a UserPartition with ID [{}]\".format(user_partition_id))\n\n def validate(self):\n \"\"\"\n Validates the state of this xblock instance.\n \"\"\"\n _ = self.runtime.service(self, \"i18n\").ugettext\n validation = super(LmsBlockMixin, self).validate()\n has_invalid_user_partitions = False\n has_invalid_groups = False\n for user_partition_id, group_ids in self.group_access.iteritems():\n try:\n user_partition = self._get_user_partition(user_partition_id)\n except NoSuchUserPartitionError:\n has_invalid_user_partitions = True\n else:\n # Skip the validation check if the partition has been disabled\n if user_partition.active:\n for group_id in group_ids:\n try:\n user_partition.get_group(group_id)\n except NoSuchUserPartitionGroupError:\n has_invalid_groups = True\n\n if has_invalid_user_partitions:\n validation.add(\n ValidationMessage(\n ValidationMessage.ERROR,\n _(u\"This component refers to deleted or invalid content group configurations.\")\n )\n )\n if has_invalid_groups:\n validation.add(\n ValidationMessage(\n ValidationMessage.ERROR,\n _(u\"This component refers to deleted or invalid content groups.\")\n )\n )\n return validation\n","repo_name":"Edraak/edx-platform","sub_path":"lms/djangoapps/lms_xblock/mixin.py","file_name":"mixin.py","file_ext":"py","file_size_in_byte":7673,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"85"} +{"seq_id":"1480551317","text":"from flask import request\nfrom flask import jsonify\n\nfrom app import db\nfrom app.models import User,Organization,Task,Task_detail\nfrom . import taskPage\nfrom app.auth import tokenUtils\nfrom app.utilsPage import downloadFile\n\nimport datetime\n\n@taskPage.route('/tasks/add',methods=['POST'])\n@tokenUtils.token_required\ndef addTask(user_id):\n\t\n\tcode = 200 \n\tmsg = \"add task success!\"\n\ttask_id = 0\n\n\tvalues = request.values\n\tname = values.get('name')\n\tgender = values.get('gender')\n\tid_card = values.get('idcard')\n\tpart = values.get('part')\n\tmethod = values.get('method')\n\ttime = values.get('time')\n\tdescription = values.get('description')\n\tfile_url = ''\n\ttry:\n\t\tfile = request.files['attachments']\n\t\tfile_url = downloadFile.uploadFile(file,user_id)\n\texcept:\n\t\tpass\n\t\n\tuser = User.query.filter_by(id = user_id).first()\n\tif user is None:\n\t\tcode = 201 \n\t\tmsg = \"this token-user not exist!\"\n\telse:\n\t\tif user.role != 2:\n\t\t\tcode = 202\n\t\t\tmsg = \"access deny!\"\n\t\telse:\n\t\t\tif name is None or gender is None or id_card is None or part is None or method is None or time is None or description is None or file_url is None:\n\t\t\t\tcode = 203\n\t\t\t\tmsg = 'parameter error!'\n\t\t\telse:\n\t\t\t\taccount = user.account\n\t\t\t\torganization = Organization.query.filter_by(account = account).first()\n\t\t\t\torganization_name = organization.belonged_organization\n\t\t\t\torganization_operator_id = organization.id\n\n\t\t\t\tcreated_time = datetime.date.today()\n\t\t\t\tstatus = 0\n\t\t\t\t\n\t\t\t\ttask = Task(name, gender,created_time,organization_name,part,status,organization_operator_id)\n\t\t\t\tdb.session.add(task)\n\t\t\t\tdb.session.commit()\n\n\t\t\t\ttask_id = task.id\n\t\t\t\tmeasuring_time = datetime.datetime.strptime(time,'%Y/%m/%d').date()\n\t\t\t\ttask_detail = Task_detail(task_id, name,gender,id_card,part,method,measuring_time,description,file_url)\n\t\t\t\tdb.session.add(task_detail)\n\n\t\t\t\torganization.addTask(True)\n\t\t\t\tdb.session.add(organization)\n\n\t\t\t\tdb.session.commit()\n\n\tjson_to_send = {\n\t\t\t'status':{\n\t\t\t\t'code':code,\n\t\t\t\t'msg':msg\n\t\t\t},\n\t\t\t'data':{\n\t\t\t\t'task_id':task_id\n\t\t\t}\n\t}\n\treturn jsonify(json_to_send)\n\n","repo_name":"Swimminghacker/api_bodyscan","sub_path":"app/taskPage/addTask.py","file_name":"addTask.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28624937676","text":"from secrets import PROJECT_API_KEY\nfrom typing import Optional\n\nfrom appwrite.client import Client\nfrom appwrite.services.database import Database\n\nfrom config import get_config\nfrom models import (\n CoffeeBag,\n CoffeeBagDocument,\n CoffeeBeanRoast,\n CoffeeCup,\n CoffeeCupDocument,\n)\n\nclient = Client()\n\n_config = get_config()\n\n(\n client.set_endpoint(_config.appwrite.api_endpoint)\n .set_project(_config.appwrite.project_id)\n .set_key(PROJECT_API_KEY)\n)\n\n\ndef _get_database() -> Database:\n db = Database(client)\n return db\n\n\ndef _get_coffee_bag_collections_id() -> str:\n return _config.appwrite.collections.coffee_bag_collection_id\n\n\ndef _get_coffee_cup_collections_id() -> str:\n return _config.appwrite.collections.coffee_cup_collection_id\n\n\n# ---- Coffee Bags ----\n\n\ndef get_coffee_bags(\n brand: Optional[str], active: Optional[bool], roast: Optional[CoffeeBeanRoast]\n) -> list[CoffeeBagDocument]:\n db = _get_database()\n\n filters = []\n if brand is not None:\n filters.append(f\"brand={brand}\")\n if active is not None:\n filters.append(f\"active={int(active)}\")\n if roast is not None:\n filters.append(f\"roast={roast}\")\n\n print(filters)\n res = db.list_documents(_get_coffee_bag_collections_id(), filters=filters)\n return [CoffeeBagDocument(**info) for info in res[\"documents\"]]\n\n\ndef get_coffee_bag(id: str) -> CoffeeBagDocument:\n db = _get_database()\n res = db.get_document(\n collection_id=_get_coffee_bag_collections_id(), document_id=id\n )\n return CoffeeBagDocument(**res)\n\n\ndef add_coffee_bag(coffee_bag: CoffeeBag) -> CoffeeBagDocument:\n db = _get_database()\n res = db.create_document(\n collection_id=_get_coffee_bag_collections_id(), data=coffee_bag.json()\n )\n return CoffeeBagDocument(**res)\n\n\n# ---- Coffee Cups ----\n\n\ndef get_coffee_cups(bag_id: Optional[str]) -> list[CoffeeCupDocument]:\n db = _get_database()\n\n filters = []\n if bag_id is not None:\n filters.append(f\"bag_id={bag_id}\")\n\n res = db.list_documents(_get_coffee_cup_collections_id(), filters=filters)\n return [CoffeeCupDocument(**info) for info in res[\"documents\"]]\n\n\ndef get_coffee_cup(id: str) -> CoffeeCupDocument:\n db = _get_database()\n res = db.get_document(\n collection_id=_get_coffee_cup_collections_id(), document_id=id\n )\n return CoffeeCupDocument(**res)\n\n\ndef add_coffee_cup(coffee_cup: CoffeeCup) -> CoffeeCupDocument:\n db = _get_database()\n res = db.create_document(\n collection_id=_get_coffee_cup_collections_id(), data=coffee_cup.json()\n )\n return CoffeeCupDocument(**res)\n","repo_name":"jhrcook/coffee-counter-appwrite-demo","sub_path":"appwrite_backend.py","file_name":"appwrite_backend.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"80"} +{"seq_id":"8932117484","text":"\"\"\"Constants for SkyQ.\"\"\"\n\nfrom homeassistant.const import STATE_OFF, STATE_UNKNOWN\n\nDOMAIN = \"skyq\"\nDOMAINBROWSER = \"skyq_browser\"\nSKYQREMOTE = \"skyqremote\"\nUNDO_UPDATE_LISTENER = \"undo_update_listener\"\n\nCONF_SOURCES = \"sources\"\nCONF_CHANNEL_SOURCES = \"channel_sources\"\nCONF_ROOM = \"room\"\nCONF_EPG_CACHE_LEN = \"epg_cache_len\"\nCONF_GEN_SWITCH = \"generate_switches_for_channels\"\nCONF_OUTPUT_PROGRAMME_IMAGE = \"output_programme_image\"\nCONF_LIVE_TV = \"live_tv\"\nCONF_COUNTRY = \"country\"\nCONF_TEST_CHANNEL = \"test_channel\"\nCONF_VOLUME_ENTITY = \"volume_entity\"\nCONF_GET_LIVE_RECORD = \"get_live_record\"\nCHANNEL_SOURCES_DISPLAY = \"channel_sources_display\"\nCHANNEL_DISPLAY = \"{0} - {1}\"\n\nCONST_DEFAULT_ROOM = \"Default Room\"\nCONST_ALIAS_FILENAME = \"skyqswitchalias.yaml\"\nCONST_SKYQ_CHANNELNO = \"skyq_channelno\"\nCONST_SKYQ_MEDIA_TYPE = \"skyq_media_type\"\nCONST_DEFAULT = \"Default\"\nCONST_DEFAULT_EPGCACHELEN = 20\nLIST_EPGCACHELEN = [10, 20, 30, 50, 999]\n\nDEVICE_CLASS = \"receiver\"\n\nFEATURE_BASIC = 1\nFEATURE_IMAGE = 2\nFEATURE_LIVE_TV = 4\nFEATURE_SWITCHES = 8\nFEATURE_GET_LIVE_RECORD = 16\n\nTIMEOUT = 2\nERROR_TIMEOUT = 10\n\nSKYQ_APP = \"app\"\nSKYQ_LIVE = \"live\"\nSKYQ_LIVEREC = \"liverecord\"\nSKYQ_PVR = \"pvr\"\nSKYQ_ICONS = {\n SKYQ_APP: \"mdi:application\",\n SKYQ_LIVE: \"mdi:satellite-variant\",\n SKYQ_LIVEREC: \"mdi:record-rec\",\n STATE_OFF: \"mdi:television\",\n SKYQ_PVR: \"mdi:movie-open\",\n STATE_UNKNOWN: \"mdi:alert-circle-outline\",\n}\nAPP_TITLES = {\n \"com.bskyb.epgui\": \"EPG\",\n \"com.bskyb.news\": \"SkyNews\",\n \"com.bskyb.vevo\": \"Vevo\",\n \"com.roku\": \"Roku\",\n \"com.skyita.dazn\": \"DAZN\",\n \"com.spotify.spotify.tvv2\": \"Spotify\",\n \"fiit.tv\": \"Fiit\",\n \"mediasetplay\": \"MediasetPlay\",\n \"play.works\": \"PlayWorks\",\n \"prime.video\": \"PrimeVideo\",\n}\nAPP_IMAGE_URL_BASE = \"/api/\" + DOMAIN + \"/static\"\n","repo_name":"IrishTLR/bruces_homeassistant_config","sub_path":"custom_components/skyq/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"50574251005","text":"import pygame\nfrom pygame.sprite import Sprite # I have to inherit Sprite to use the Group class\n\nclass Ship(Sprite):\n \"\"\" This class holds information relative to the player object, the ship.\n It has methods to draw it, and its constructor fetches information \n from pygame to give it context-appropriate attributes. \"\"\"\n\n def __init__(self, settings, screen):\n # During initialization, the ship should reference which screen\n # it should be drawn on, and collect some stats about it\n super().__init__()\n self.screen = screen\n self.settings = settings\n self.screen_rect = self.screen.get_rect()\n\n # Get the ship picture and store statistics about it\n self.color = 'green' # ok for green, blue, red or yellow\n self.image = pygame.image.load(\"../images/ship_\" + self.color + \".png\").convert_alpha()\n self.rect = self.image.get_rect()\n\n # The ship should spawn in the middle of the screen, bottom row\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n\n # Store a float for the center to make it smooth\n self.center = float(self.rect.centerx)\n\n # Movement flags\n self.moving_right = False\n self.moving_left = False\n \n def blit_me(self):\n # blit(what, where)\n self.screen.blit(self.image, self.rect)\n\n def update(self):\n # This method relies on the movement flags set up during init()\n if self.moving_right and self.rect.right < self.screen_rect.right:\n self.center += self.settings.ship_speed_factor\n if self.moving_left and self.rect.left > 0:\n self.center -= self.settings.ship_speed_factor\n\n # Update coordinates\n self.rect.centerx = self.center\n","repo_name":"orenofrancisco/study-python-game","sub_path":"src/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5317408651","text":"# -*- coding: utf-8 -*-\nimport sys\nimport argparse\nimport socket\n\ndef scan_port(ser=None, begin=None, end=None, timeout=None, verbose=True):\n ser = ser or 'localhost'\n begin = begin or 0\n end = end or 65536\n timeout = timeout or 0.1\n\n rv = []\n c = socket.socket()\n begin = max(begin, 1)\n end = min(end, 65536)\n for port in range(begin, end):\n if verbose:\n msg = \"\\rchecking on (%15s, %5s), avaliable port: %4d \" % (ser, port, len(rv))\n sys.stderr.write(msg)\n c.__init__()\n c.settimeout(timeout)\n ret = c.connect_ex((ser, port))\n if ret == 0:\n rv.append((ser, port))\n c.close()\n\n return rv\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"qsc 自制端口扫描工具\")\n parser.add_argument(\"--host\", dest=\"host\", type=str, help=\"host, eg: localhost, www.baidu.com, 127.0.0.1\")\n parser.add_argument(\"--begin\", '-b', dest=\"begin\", type=int, help=\"扫描端口的起始端口\")\n parser.add_argument(\"--end\", '-e', dest=\"end\", type=int, help=\"扫描端口的结束端口\")\n parser.add_argument(\"--timeout\", '-t', dest=\"timeout\", type=float, help=\"连接超时时间\")\n\n args = parser.parse_args()\n print(args)\n rv = scan_port(args.host, args.begin, args.end, args.timeout)\n\n print()\n for item in rv:\n print(item)\n\n","repo_name":"akxxsb/utils","sub_path":"cmd/port_scan.py","file_name":"port_scan.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"31444332149","text":"from django.db import transaction\nfrom rest_framework import serializers\nfrom ordering.models import Customer, Item, Order, OrderItems\n\n\nclass ItemSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField()\n name = serializers.CharField()\n\n class Meta:\n model = Item\n fields = ['id', 'name']\n depth = 1\n\n\nclass CustomerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Customer\n fields = ['id', 'name', 'mobile', 'orders']\n depth = 1\n\n\nclass CustomersSerializer(serializers.ModelSerializer):\n class Meta:\n model = Customer\n fields = ['name', 'mobile']\n depth = 1\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField(read_only=True)\n customer_id = serializers.IntegerField(required=True)\n item = ItemSerializer(many=True, required=True)\n\n class Meta:\n model = Order\n fields = ['id', 'date', 'customer_id', 'item', ]\n\n def create(self, validated_data):\n item_data = validated_data.pop('item', [])\n with transaction.atomic():\n order = Order(**validated_data)\n order.save()\n through = order.item.through\n objects = []\n for item in item_data:\n objects.append(through(item_id=item[\"id\"], order_id=order.id))\n through.objects.bulk_create(objects)\n return order\n\n def update(self, instance, validated_data):\n items_data = validated_data.pop('item', None)\n for key, value in validated_data.items():\n setattr(instance, key, value)\n instance.save()\n if items_data is not None:\n OrderItems.objects.filter(order=instance).delete()\n for item in items_data:\n OrderItems.objects.create(order=instance, item_id=item['id'])\n return instance\n\n\nclass OrderItemsSerializer(serializers.ModelSerializer):\n class Meta:\n model = OrderItems\n fields = ['item']\n","repo_name":"Farah-POSRocket/Ordering-System","sub_path":"ordering/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"43540936748","text":"import torch\nimport torch.nn as nn\nfrom collections import OrderedDict\n\n\nclass BatchNorm1dNoBias(nn.BatchNorm1d):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.bias.requires_grad = False\n \n \nclass LSTM(nn.Module):\n def __init__(self, *, in_features, out_features, max_seq_len,\n num_lstm_out=100, num_lstm_layers=1):\n super().__init__()\n self.in_features = in_features\n self.max_seq_len = max_seq_len\n self.out_features = out_features\n\n self.num_lstm_out = num_lstm_out\n self.num_lstm_layers = num_lstm_layers\n\n self.lstm = nn.LSTM(input_size=self.in_features, \n hidden_size=self.num_lstm_out,\n num_layers=self.num_lstm_layers,\n batch_first=True)\n\n self.proj_dim = self.out_features\n projection_layers = [\n ('fc1', nn.Linear(self.num_lstm_out, self.num_lstm_out, bias=False)),\n ('bn1', nn.BatchNorm1d(self.num_lstm_out)),\n ('act', nn.GELU()),\n ('fc2', nn.Linear(self.num_lstm_out, self.proj_dim, bias=False)),\n ('bn2', BatchNorm1dNoBias(self.proj_dim)),\n ]\n self.projection = nn.Sequential(OrderedDict(projection_layers))\n \n \n def forward(self, x, seq_lens):\n x1 = nn.utils.rnn.pack_padded_sequence(x, seq_lens.cpu(), \n batch_first=True, \n enforce_sorted=False)\n x1, (ht,ct) = self.lstm(x1)\n x1, _ = nn.utils.rnn.pad_packed_sequence(x1, batch_first=True, \n padding_value=0.0)\n x1 = x1[:,-1,:]\n \n x_out = self.projection(x1)\n return x_out","repo_name":"33H002/torch_project","sub_path":"script/model/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16696121921","text":"from django.views import generic\nfrom django.contrib.gis.geos import Point\nfrom django.contrib.gis.db.models.functions import Distance\nfrom django.shortcuts import render, get_object_or_404, redirect, reverse\nfrom .models import Shop\n\nlongitude = 1\nlatitude = 1\n\nuser_location = Point(longitude, latitude, srid=4326)\n\nclass Home(generic.ListView):\n \n def post(self, request, *args, **kwargs):\n try:\n latitude = float(request.POST.get(\"latitude\"))\n longitude = float(request.POST.get(\"longitude\"))\n\n user_location = Point(longitude, latitude, srid=4326)\n queryset = Shop.objects.annotate( \n distance=Distance(\"location\",user_location)\n ).order_by(\"distance\")[0:10]\n context = {'shops':queryset}\n \n return render(request, 'index.html',context)\n\n \n except:\n return redirect('/') \n \n\n\n model = Shop\n context_object_name = \"shops\"\n queryset = Shop.objects.annotate(\n distance=Distance(\"location\",user_location)\n ).order_by(\"distance\")[0:10]\n template_name = \"index.html\"\n\n \n\n\nhome = Home.as_view()","repo_name":"githsem/Django_PostGIS-Location_WebApp","sub_path":"nearbyshops/shops/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"1460669386","text":"from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import Timestamp\n\nimport pandas as pd\nfrom pandas import Float64Index, Index, Int64Index, RangeIndex, Series, UInt64Index\nimport pandas._testing as tm\nfrom pandas.tests.indexes.common import Base\n\n\nclass TestArithmetic:\n @pytest.mark.parametrize(\n \"klass\", [Float64Index, Int64Index, UInt64Index, RangeIndex]\n )\n def test_arithmetic_explicit_conversions(self, klass):\n\n # GH 8608\n # add/sub are overridden explicitly for Float/Int Index\n if klass is RangeIndex:\n idx = RangeIndex(5)\n else:\n idx = klass(np.arange(5, dtype=\"int64\"))\n\n # float conversions\n arr = np.arange(5, dtype=\"int64\") * 3.2\n expected = Float64Index(arr)\n fidx = idx * 3.2\n tm.assert_index_equal(fidx, expected)\n fidx = 3.2 * idx\n tm.assert_index_equal(fidx, expected)\n\n # interops with numpy arrays\n expected = Float64Index(arr)\n a = np.zeros(5, dtype=\"float64\")\n result = fidx - a\n tm.assert_index_equal(result, expected)\n\n expected = Float64Index(-arr)\n a = np.zeros(5, dtype=\"float64\")\n result = a - fidx\n tm.assert_index_equal(result, expected)\n\n\nclass TestNumericIndex:\n def test_index_groupby(self):\n int_idx = Index(range(6))\n float_idx = Index(np.arange(0, 0.6, 0.1))\n obj_idx = Index(\"A B C D E F\".split())\n dt_idx = pd.date_range(\"2013-01-01\", freq=\"M\", periods=6)\n\n for idx in [int_idx, float_idx, obj_idx, dt_idx]:\n to_groupby = np.array([1, 2, np.nan, np.nan, 2, 1])\n tm.assert_dict_equal(\n idx.groupby(to_groupby), {1.0: idx[[0, 5]], 2.0: idx[[1, 4]]}\n )\n\n to_groupby = Index(\n [\n datetime(2011, 11, 1),\n datetime(2011, 12, 1),\n pd.NaT,\n pd.NaT,\n datetime(2011, 12, 1),\n datetime(2011, 11, 1),\n ],\n tz=\"UTC\",\n ).values\n\n ex_keys = [Timestamp(\"2011-11-01\"), Timestamp(\"2011-12-01\")]\n expected = {ex_keys[0]: idx[[0, 5]], ex_keys[1]: idx[[1, 4]]}\n tm.assert_dict_equal(idx.groupby(to_groupby), expected)\n\n\nclass Numeric(Base):\n def test_where(self):\n # Tested in numeric.test_indexing\n pass\n\n def test_can_hold_identifiers(self):\n idx = self.create_index()\n key = idx[0]\n assert idx._can_hold_identifiers_and_holds_name(key) is False\n\n def test_format(self):\n # GH35439\n idx = self.create_index()\n max_width = max(len(str(x)) for x in idx)\n expected = [str(x).ljust(max_width) for x in idx]\n assert idx.format() == expected\n\n def test_numeric_compat(self):\n pass # override Base method\n\n def test_insert_na(self, nulls_fixture):\n # GH 18295 (test missing)\n index = self.create_index()\n\n if nulls_fixture is pd.NaT:\n expected = Index([index[0], pd.NaT] + list(index[1:]), dtype=object)\n else:\n expected = Float64Index([index[0], np.nan] + list(index[1:]))\n result = index.insert(1, nulls_fixture)\n tm.assert_index_equal(result, expected)\n\n\nclass TestFloat64Index(Numeric):\n _holder = Float64Index\n\n @pytest.fixture(\n params=[\n [1.5, 2, 3, 4, 5],\n [0.0, 2.5, 5.0, 7.5, 10.0],\n [5, 4, 3, 2, 1.5],\n [10.0, 7.5, 5.0, 2.5, 0.0],\n ],\n ids=[\"mixed\", \"float\", \"mixed_dec\", \"float_dec\"],\n )\n def index(self, request):\n return Float64Index(request.param)\n\n @pytest.fixture\n def mixed_index(self):\n return Float64Index([1.5, 2, 3, 4, 5])\n\n @pytest.fixture\n def float_index(self):\n return Float64Index([0.0, 2.5, 5.0, 7.5, 10.0])\n\n def create_index(self) -> Float64Index:\n return Float64Index(np.arange(5, dtype=\"float64\"))\n\n def test_repr_roundtrip(self, index):\n tm.assert_index_equal(eval(repr(index)), index)\n\n def check_is_index(self, i):\n assert isinstance(i, Index)\n assert not isinstance(i, Float64Index)\n\n def check_coerce(self, a, b, is_float_index=True):\n assert a.equals(b)\n tm.assert_index_equal(a, b, exact=False)\n if is_float_index:\n assert isinstance(b, Float64Index)\n else:\n self.check_is_index(b)\n\n def test_constructor(self):\n\n # explicit construction\n index = Float64Index([1, 2, 3, 4, 5])\n assert isinstance(index, Float64Index)\n expected = np.array([1, 2, 3, 4, 5], dtype=\"float64\")\n tm.assert_numpy_array_equal(index.values, expected)\n index = Float64Index(np.array([1, 2, 3, 4, 5]))\n assert isinstance(index, Float64Index)\n index = Float64Index([1.0, 2, 3, 4, 5])\n assert isinstance(index, Float64Index)\n index = Float64Index(np.array([1.0, 2, 3, 4, 5]))\n assert isinstance(index, Float64Index)\n assert index.dtype == float\n\n index = Float64Index(np.array([1.0, 2, 3, 4, 5]), dtype=np.float32)\n assert isinstance(index, Float64Index)\n assert index.dtype == np.float64\n\n index = Float64Index(np.array([1, 2, 3, 4, 5]), dtype=np.float32)\n assert isinstance(index, Float64Index)\n assert index.dtype == np.float64\n\n # nan handling\n result = Float64Index([np.nan, np.nan])\n assert pd.isna(result.values).all()\n result = Float64Index(np.array([np.nan]))\n assert pd.isna(result.values).all()\n result = Index(np.array([np.nan]))\n assert pd.isna(result.values).all()\n\n @pytest.mark.parametrize(\n \"index, dtype\",\n [\n (Int64Index, \"float64\"),\n (UInt64Index, \"categorical\"),\n (Float64Index, \"datetime64\"),\n (RangeIndex, \"float64\"),\n ],\n )\n def test_invalid_dtype(self, index, dtype):\n # GH 29539\n with pytest.raises(\n ValueError,\n match=rf\"Incorrect `dtype` passed: expected \\w+(?: \\w+)?, received {dtype}\",\n ):\n index([1, 2, 3], dtype=dtype)\n\n def test_constructor_invalid(self):\n\n # invalid\n msg = (\n r\"Float64Index\\(\\.\\.\\.\\) must be called with a collection of \"\n r\"some kind, 0\\.0 was passed\"\n )\n with pytest.raises(TypeError, match=msg):\n Float64Index(0.0)\n\n # 2021-02-1 we get ValueError in numpy 1.20, but not on all builds\n msg = \"|\".join(\n [\n \"String dtype not supported, you may need to explicitly cast \",\n \"could not convert string to float: 'a'\",\n ]\n )\n with pytest.raises((TypeError, ValueError), match=msg):\n Float64Index([\"a\", \"b\", 0.0])\n\n msg = r\"float\\(\\) argument must be a string or a number, not 'Timestamp'\"\n with pytest.raises(TypeError, match=msg):\n Float64Index([Timestamp(\"20130101\")])\n\n def test_constructor_coerce(self, mixed_index, float_index):\n\n self.check_coerce(mixed_index, Index([1.5, 2, 3, 4, 5]))\n self.check_coerce(float_index, Index(np.arange(5) * 2.5))\n self.check_coerce(\n float_index, Index(np.array(np.arange(5) * 2.5, dtype=object))\n )\n\n def test_constructor_explicit(self, mixed_index, float_index):\n\n # these don't auto convert\n self.check_coerce(\n float_index, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False\n )\n self.check_coerce(\n mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False\n )\n\n def test_type_coercion_fail(self, any_int_dtype):\n # see gh-15832\n msg = \"Trying to coerce float values to integers\"\n with pytest.raises(ValueError, match=msg):\n Index([1, 2, 3.5], dtype=any_int_dtype)\n\n def test_type_coercion_valid(self, float_dtype):\n # There is no Float32Index, so we always\n # generate Float64Index.\n i = Index([1, 2, 3.5], dtype=float_dtype)\n tm.assert_index_equal(i, Index([1, 2, 3.5]))\n\n def test_equals_numeric(self):\n\n i = Float64Index([1.0, 2.0])\n assert i.equals(i)\n assert i.identical(i)\n\n i2 = Float64Index([1.0, 2.0])\n assert i.equals(i2)\n\n i = Float64Index([1.0, np.nan])\n assert i.equals(i)\n assert i.identical(i)\n\n i2 = Float64Index([1.0, np.nan])\n assert i.equals(i2)\n\n @pytest.mark.parametrize(\n \"other\",\n (\n Int64Index([1, 2]),\n Index([1.0, 2.0], dtype=object),\n Index([1, 2], dtype=object),\n ),\n )\n def test_equals_numeric_other_index_type(self, other):\n i = Float64Index([1.0, 2.0])\n assert i.equals(other)\n assert other.equals(i)\n\n @pytest.mark.parametrize(\n \"vals\",\n [\n pd.date_range(\"2016-01-01\", periods=3),\n pd.timedelta_range(\"1 Day\", periods=3),\n ],\n )\n def test_lookups_datetimelike_values(self, vals):\n # If we have datetime64 or timedelta64 values, make sure they are\n # wrappped correctly GH#31163\n ser = Series(vals, index=range(3, 6))\n ser.index = ser.index.astype(\"float64\")\n\n expected = vals[1]\n\n with tm.assert_produces_warning(FutureWarning):\n result = ser.index.get_value(ser, 4.0)\n assert isinstance(result, type(expected)) and result == expected\n with tm.assert_produces_warning(FutureWarning):\n result = ser.index.get_value(ser, 4)\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser[4.0]\n assert isinstance(result, type(expected)) and result == expected\n result = ser[4]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.loc[4.0]\n assert isinstance(result, type(expected)) and result == expected\n result = ser.loc[4]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.at[4.0]\n assert isinstance(result, type(expected)) and result == expected\n # GH#31329 .at[4] should cast to 4.0, matching .loc behavior\n result = ser.at[4]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.iloc[1]\n assert isinstance(result, type(expected)) and result == expected\n\n result = ser.iat[1]\n assert isinstance(result, type(expected)) and result == expected\n\n def test_doesnt_contain_all_the_things(self):\n i = Float64Index([np.nan])\n assert not i.isin([0]).item()\n assert not i.isin([1]).item()\n assert i.isin([np.nan]).item()\n\n def test_nan_multiple_containment(self):\n i = Float64Index([1.0, np.nan])\n tm.assert_numpy_array_equal(i.isin([1.0]), np.array([True, False]))\n tm.assert_numpy_array_equal(i.isin([2.0, np.pi]), np.array([False, False]))\n tm.assert_numpy_array_equal(i.isin([np.nan]), np.array([False, True]))\n tm.assert_numpy_array_equal(i.isin([1.0, np.nan]), np.array([True, True]))\n i = Float64Index([1.0, 2.0])\n tm.assert_numpy_array_equal(i.isin([np.nan]), np.array([False, False]))\n\n def test_fillna_float64(self):\n # GH 11343\n idx = Index([1.0, np.nan, 3.0], dtype=float, name=\"x\")\n # can't downcast\n exp = Index([1.0, 0.1, 3.0], name=\"x\")\n tm.assert_index_equal(idx.fillna(0.1), exp)\n\n # downcast\n exp = Float64Index([1.0, 2.0, 3.0], name=\"x\")\n tm.assert_index_equal(idx.fillna(2), exp)\n\n # object\n exp = Index([1.0, \"obj\", 3.0], name=\"x\")\n tm.assert_index_equal(idx.fillna(\"obj\"), exp)\n\n\nclass NumericInt(Numeric):\n def test_view(self):\n i = self._holder([], name=\"Foo\")\n i_view = i.view()\n assert i_view.name == \"Foo\"\n\n i_view = i.view(self._dtype)\n tm.assert_index_equal(i, self._holder(i_view, name=\"Foo\"))\n\n i_view = i.view(self._holder)\n tm.assert_index_equal(i, self._holder(i_view, name=\"Foo\"))\n\n def test_is_monotonic(self):\n index = self._holder([1, 2, 3, 4])\n assert index.is_monotonic is True\n assert index.is_monotonic_increasing is True\n assert index._is_strictly_monotonic_increasing is True\n assert index.is_monotonic_decreasing is False\n assert index._is_strictly_monotonic_decreasing is False\n\n index = self._holder([4, 3, 2, 1])\n assert index.is_monotonic is False\n assert index._is_strictly_monotonic_increasing is False\n assert index._is_strictly_monotonic_decreasing is True\n\n index = self._holder([1])\n assert index.is_monotonic is True\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_increasing is True\n assert index._is_strictly_monotonic_decreasing is True\n\n def test_is_strictly_monotonic(self):\n index = self._holder([1, 1, 2, 3])\n assert index.is_monotonic_increasing is True\n assert index._is_strictly_monotonic_increasing is False\n\n index = self._holder([3, 2, 1, 1])\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_decreasing is False\n\n index = self._holder([1, 1])\n assert index.is_monotonic_increasing\n assert index.is_monotonic_decreasing\n assert not index._is_strictly_monotonic_increasing\n assert not index._is_strictly_monotonic_decreasing\n\n def test_logical_compat(self):\n idx = self.create_index()\n assert idx.all() == idx.values.all()\n assert idx.any() == idx.values.any()\n\n def test_identical(self):\n index = self.create_index()\n i = Index(index.copy())\n assert i.identical(index)\n\n same_values_different_type = Index(i, dtype=object)\n assert not i.identical(same_values_different_type)\n\n i = index.astype(dtype=object)\n i = i.rename(\"foo\")\n same_values = Index(i, dtype=object)\n assert same_values.identical(i)\n\n assert not i.identical(index)\n assert Index(same_values, name=\"foo\", dtype=object).identical(i)\n\n assert not index.astype(dtype=object).identical(index.astype(dtype=self._dtype))\n\n def test_cant_or_shouldnt_cast(self):\n msg = (\n \"String dtype not supported, \"\n \"you may need to explicitly cast to a numeric type\"\n )\n # can't\n data = [\"foo\", \"bar\", \"baz\"]\n with pytest.raises(TypeError, match=msg):\n self._holder(data)\n\n # shouldn't\n data = [\"0\", \"1\", \"2\"]\n with pytest.raises(TypeError, match=msg):\n self._holder(data)\n\n def test_view_index(self):\n index = self.create_index()\n index.view(Index)\n\n def test_prevent_casting(self):\n index = self.create_index()\n result = index.astype(\"O\")\n assert result.dtype == np.object_\n\n\nclass TestInt64Index(NumericInt):\n _dtype = \"int64\"\n _holder = Int64Index\n\n @pytest.fixture(\n params=[range(0, 20, 2), range(19, -1, -1)], ids=[\"index_inc\", \"index_dec\"]\n )\n def index(self, request):\n return Int64Index(request.param)\n\n def create_index(self) -> Int64Index:\n # return Int64Index(np.arange(5, dtype=\"int64\"))\n return Int64Index(range(0, 20, 2))\n\n def test_constructor(self):\n # pass list, coerce fine\n index = Int64Index([-5, 0, 1, 2])\n expected = Index([-5, 0, 1, 2], dtype=np.int64)\n tm.assert_index_equal(index, expected)\n\n # from iterable\n index = Int64Index(iter([-5, 0, 1, 2]))\n tm.assert_index_equal(index, expected)\n\n # scalar raise Exception\n msg = (\n r\"Int64Index\\(\\.\\.\\.\\) must be called with a collection of some \"\n \"kind, 5 was passed\"\n )\n with pytest.raises(TypeError, match=msg):\n Int64Index(5)\n\n # copy\n arr = index.values\n new_index = Int64Index(arr, copy=True)\n tm.assert_index_equal(new_index, index)\n val = arr[0] + 3000\n\n # this should not change index\n arr[0] = val\n assert new_index[0] != val\n\n # interpret list-like\n expected = Int64Index([5, 0])\n for cls in [Index, Int64Index]:\n for idx in [\n cls([5, 0], dtype=\"int64\"),\n cls(np.array([5, 0]), dtype=\"int64\"),\n cls(Series([5, 0]), dtype=\"int64\"),\n ]:\n tm.assert_index_equal(idx, expected)\n\n def test_constructor_corner(self):\n arr = np.array([1, 2, 3, 4], dtype=object)\n index = Int64Index(arr)\n assert index.values.dtype == np.int64\n tm.assert_index_equal(index, Index(arr))\n\n # preventing casting\n arr = np.array([1, \"2\", 3, \"4\"], dtype=object)\n with pytest.raises(TypeError, match=\"casting\"):\n Int64Index(arr)\n\n arr_with_floats = [0, 2, 3, 4, 5, 1.25, 3, -1]\n with pytest.raises(TypeError, match=\"casting\"):\n Int64Index(arr_with_floats)\n\n def test_constructor_coercion_signed_to_unsigned(self, uint_dtype):\n\n # see gh-15832\n msg = \"Trying to coerce negative values to unsigned integers\"\n\n with pytest.raises(OverflowError, match=msg):\n Index([-1], dtype=uint_dtype)\n\n def test_constructor_unwraps_index(self):\n idx = Index([1, 2])\n result = Int64Index(idx)\n expected = np.array([1, 2], dtype=\"int64\")\n tm.assert_numpy_array_equal(result._data, expected)\n\n def test_coerce_list(self):\n # coerce things\n arr = Index([1, 2, 3, 4])\n assert isinstance(arr, Int64Index)\n\n # but not if explicit dtype passed\n arr = Index([1, 2, 3, 4], dtype=object)\n assert isinstance(arr, Index)\n\n\nclass TestUInt64Index(NumericInt):\n\n _dtype = \"uint64\"\n _holder = UInt64Index\n\n @pytest.fixture(\n params=[\n [2 ** 63, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20, 2 ** 63 + 25],\n [2 ** 63 + 25, 2 ** 63 + 20, 2 ** 63 + 15, 2 ** 63 + 10, 2 ** 63],\n ],\n ids=[\"index_inc\", \"index_dec\"],\n )\n def index(self, request):\n return UInt64Index(request.param)\n\n def create_index(self) -> UInt64Index:\n # compat with shared Int64/Float64 tests\n return UInt64Index(np.arange(5, dtype=\"uint64\"))\n\n def test_constructor(self):\n idx = UInt64Index([1, 2, 3])\n res = Index([1, 2, 3], dtype=np.uint64)\n tm.assert_index_equal(res, idx)\n\n idx = UInt64Index([1, 2 ** 63])\n res = Index([1, 2 ** 63], dtype=np.uint64)\n tm.assert_index_equal(res, idx)\n\n idx = UInt64Index([1, 2 ** 63])\n res = Index([1, 2 ** 63])\n tm.assert_index_equal(res, idx)\n\n idx = Index([-1, 2 ** 63], dtype=object)\n res = Index(np.array([-1, 2 ** 63], dtype=object))\n tm.assert_index_equal(res, idx)\n\n # https://github.com/pandas-dev/pandas/issues/29526\n idx = UInt64Index([1, 2 ** 63 + 1], dtype=np.uint64)\n res = Index([1, 2 ** 63 + 1], dtype=np.uint64)\n tm.assert_index_equal(res, idx)\n\n\n@pytest.mark.parametrize(\n \"box\",\n [list, lambda x: np.array(x, dtype=object), lambda x: Index(x, dtype=object)],\n)\ndef test_uint_index_does_not_convert_to_float64(box):\n # https://github.com/pandas-dev/pandas/issues/28279\n # https://github.com/pandas-dev/pandas/issues/28023\n series = Series(\n [0, 1, 2, 3, 4, 5],\n index=[\n 7606741985629028552,\n 17876870360202815256,\n 17876870360202815256,\n 13106359306506049338,\n 8991270399732411471,\n 8991270399732411472,\n ],\n )\n\n result = series.loc[box([7606741985629028552, 17876870360202815256])]\n\n expected = UInt64Index(\n [7606741985629028552, 17876870360202815256, 17876870360202815256],\n dtype=\"uint64\",\n )\n tm.assert_index_equal(result.index, expected)\n\n tm.assert_equal(result, series[:3])\n\n\ndef test_float64_index_equals():\n # https://github.com/pandas-dev/pandas/issues/35217\n float_index = Index([1.0, 2, 3])\n string_index = Index([\"1\", \"2\", \"3\"])\n\n result = float_index.equals(string_index)\n assert result is False\n\n result = string_index.equals(float_index)\n assert result is False\n","repo_name":"thebaselab/codeapp","sub_path":"LanguageResources/Library/lib/python3.9/site-packages/pandas/tests/indexes/test_numeric.py","file_name":"test_numeric.py","file_ext":"py","file_size_in_byte":20600,"program_lang":"python","lang":"en","doc_type":"code","stars":2422,"dataset":"github-code","pt":"80"} +{"seq_id":"32467686154","text":"# coding:utf-8\n# --author-- lanhua.zhou\nfrom __future__ import print_function\n\nimport os\nimport logging\n\nimport maya.cmds as cmds\n\nimport zfused_api\n\nfrom zcore import zfile,transfer\n\nimport zfused_maya.node.core.clear as clear\nimport zfused_maya.node.core.alembiccache as alembiccache\nimport zfused_maya.node.core.texture as texture\nimport zfused_maya.node.core.material as material\nimport zfused_maya.node.core.fixmeshname as fixmeshname\nimport zfused_maya.node.core.renderinggroup as renderinggroup\n\n__all__ = [\"export_file\"]\n\nlogger = logging.getLogger(__name__)\n\ndef export_file(*args, **kwargs):\n \"\"\" 上传任务模型文件\n args: entity_type, entity_id, attr_id\n \"\"\"\n _entity_type, _entity_id, _attr_id = args\n \n # attr\n _output_attr_handle = zfused_api.outputattr.OutputAttr(_attr_id)\n _suffix = _output_attr_handle.suffix()\n _file_format = _output_attr_handle.format()\n _attr_path = _output_attr_handle.path()\n \n # project step \n _project_step_id = _output_attr_handle.data()[\"ProjectStepId\"]\n _project_step_handle = zfused_api.step.ProjectStep(_project_step_id)\n _project_step_path = _project_step_handle.path()\n\n # entity \n _entity_handle = zfused_api.objects.Objects(_entity_type, _entity_id)\n _entity_path = _entity_handle.path()\n\n # project \n _project_handle = _entity_handle.project()\n _project_production_path = _project_handle.production_path()\n _project_temp_path = _project_handle.temp_path()\n\n # task\n _task = _entity_handle.tasks([_project_step_id])[0]\n _task_id = _task[\"Id\"]\n _task_handle = zfused_api.task.Task(_task_id)\n if kwargs.get(\"fix_version\"):\n _file_index = \"{:0>4d}\".format(_task_handle.last_version_index( 0 ))\n else:\n _file_index = \"{:0>4d}\".format(_task_handle.last_version_index() + 1)\n _file_name = \"{}.{}{}\".format(_entity_handle.code(),_file_index,_suffix)\n _cover_name = \"{}{}\".format(_entity_handle.code(),_suffix)\n\n _production_file = \"{}/{}/{}/{}/{}\".format( _project_production_path, _entity_path, _project_step_path, _attr_path, _file_name )\n _production_file_dir = os.path.dirname(_production_file)\n _cover_file = \"{}/{}/{}/{}/{}\".format( _project_production_path, _entity_path, _project_step_path, _attr_path, _cover_name )\n _publish_file = \"{}/{}/{}/{}/{}\".format( _project_temp_path, _entity_path, _project_step_path, _attr_path, _file_name )\n _publish_file_dir = os.path.dirname(_publish_file)\n if not os.path.isdir(_publish_file_dir):\n os.makedirs(_publish_file_dir)\n try:\n # save publish file\n cmds.file(rename = _publish_file)\n cmds.file(save = True, type = _file_format, f = True, options = \"v=0;\")\n # fix mesh name\n _is_rendering = renderinggroup.nodes()\n fixmeshname.fix_mesh_name(\"_rendering\", _is_rendering)\n # recore material\n material.record()\n # publish texture\n _texture_files = texture.files()\n if _texture_files:\n _texture_path = \"{}/{}/texture\".format(_project_production_path,_entity_path)\n _path_set = texture.paths(_texture_files)[0]\n _intersection_path = max(_path_set)\n texture.publish_file(_texture_files, _intersection_path, _texture_path)\n # change maya texture node path\n _file_nodes = texture.nodes()\n if _file_nodes:\n texture.change_node_path(_file_nodes, _intersection_path, _texture_path)\n \n # publish alembic cache\n _alembic_files = alembiccache.files()\n if _alembic_files:\n _alembic_path = \"{}/{}/cache/alembic\".format(_project_production_path,_entity_path)\n _path_set = alembiccache.paths(_alembic_files)[0]\n _intersection_path = max(_path_set)\n alembiccache.publish_file(_alembic_files, _intersection_path, _alembic_path)\n _file_nodes = alembiccache.nodes()\n # change alembic path\n if _file_nodes:\n alembiccache.change_node_path(_file_nodes, _intersection_path, _alembic_path)\n \n # save publish file\n cmds.file(save = True, type = _file_format, f = True, options = \"v=0;\")\n \n # publish file\n # _result = filefunc.publish_file(_publish_file, _production_file)\n # _result = filefunc.publish_file(_publish_file, _cover_file)\n transfer.send_file_to_server(_publish_file, _production_file)\n transfer.send_file_to_server(_publish_file, _cover_file)\n \n # record in database\n _file_info = zfile.get_file_info(_publish_file, _production_file)\n zfused_api.task.new_production_file([_file_info], _task_id, _attr_id, int(_file_index) )\n\n # link files\n zfused_api.files.new_file(\"task\", _task_id, _production_file, int(_file_index))\n zfused_api.files.new_file(\"task\", _task_id, _cover_file, int(_file_index))\n except Exception as e:\n logger.error(e)\n return False\n\n return True\n\nif __name__ == '__main__':\n publish_file()","repo_name":"ReHuHuDeLengKaFei/zfused_outsource","sub_path":"zfused_maya/zfused_maya/node/outputattr/modeling/export_file.py","file_name":"export_file.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"12892362478","text":"'''\nCreated on 15.02.2015\n\n@author: diesel\n'''\n\nclass IndexRangeData(object):\n '''\n classdocs\n '''\n\n\n def __init__(self):\n '''\n Constructor\n '''\n\n def setData(self, resultHistory):\n self.firstEntry = resultHistory[0]\n self.lastEntry = resultHistory[len(resultHistory)-1]\n self.maxClose = 0\n self.minClose = 1000000000\n self.maxHigh = 0\n self.minLow = self.minClose\n\n for entry in resultHistory:\n if entry.close > self.maxClose:\n self.maxClose = entry.close\n\n if entry.close < self.minClose:\n self.minClose = entry.close\n\n if entry.high > self.maxHigh:\n self.maxHigh = entry.high\n\n if entry.low < self.minLow:\n self.minLow = entry.low\n\n","repo_name":"selentd/pythontools","sub_path":"pytools/src/IndexEval/indexrangedata.py","file_name":"indexrangedata.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"41908147010","text":"import matplotlib\nfrom Utility_LSTM import *\nmatplotlib.use(\"TkAgg\") # Do this before importing pyplot!\nimport matplotlib.pyplot as plt\nplt.interactive(True)\nimport pickle\nimport shap\nfrom keras.utils import plot_model\nimport time\ndef main():\n print(\"init\")\n trained_model = open('../results/trained_net_rischio4_voronoi.p',\"rb\")\n model = pickle.load(trained_model)\n model_history = open('../results/history_rischio4_voronoi.p',\"rb\")\n history = pickle.load(model_history)\n title = \"../datasets/test_set_rischio4_voronoi_strat.p\"\n test = open(title,\"rb\")\n test_set = pickle.load(test)\n title = \"../datasets/test_label_rischio4_voronoi_strat.p\"\n test_l = open(title,\"rb\")\n test_label = pickle.load(test_l)\n path = '../results/'\n classifier = Utility_LSTM(path, 'rischio4_voronoi')\n start_time = time.time()\n #plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)\n classifier.prediction_classifier(model, test_set, test_label)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n #classifier.plot_accuracy(history)\n classifier.plot_loss_vs_epoch(history)\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"francescanaretto/Privacy-Risk-onMobility-Data-with-LSTMs","sub_path":"code/analysis_lstm.py","file_name":"analysis_lstm.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40036450389","text":"class Solution:\n def shortestPath(self, grid, k) -> int:\n if not any(grid):\n return -1\n m, n = len(grid), len(grid[0])\n k = min(k, m+n-3)\n q = [(0, 0, k, 0)]\n visited = {(0, 0, k)}\n while q:\n x, y, rest, steps = q.pop(0)\n if x == m-1 and y == n-1:\n return steps\n for nx, ny in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:\n if 0 <= nx < m and 0 <= ny < n:\n nk = rest-grid[nx][ny]\n if nk < 0 or (nx, ny, nk) in visited:\n continue\n q.append((nx, ny, nk, steps+1))\n visited.add((nx, ny, nk))\n return -1\n\n\nif __name__ == \"__main__\":\n inp = []\n try:\n while True:\n inp.append(input())\n except EOFError:\n s = Solution()\n lent = len(inp)\n K = int(inp[lent-1])\n arr = []\n for i in range(0, lent-1):\n save = []\n for j in range(0, len(inp[i])):\n if inp[i][j].isdigit():\n save.append(int(inp[i][j]))\n arr.append(save)\n res = s.shortestPath(arr, K)\n print(res)\n","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2769/60640/300203.py","file_name":"300203.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"35895477747","text":"# LEARNING PATH - Take your first steps with Python\n\n# CHALLENGE - IF ... ELSE Statement\n\ndef challenge(msg):\n if msg == \"no\" or msg == \"n\":\n return \"Exiting\"\n elif msg == \"yes\" or msg == \"y\":\n return \"Continuing ...\\nComplete!\"\n else:\n return \"Please try again and respond with yes or no.\"\n\n#message = input(\"Would you like to continue? \")\n\n\n# CHALLENGE - Manipulate and format string data for display in Python\n\nfirst_value = ' FIRST challenge '\nsecond_value = '- second challenge -'\nthird_value = 'tH IR D-C HALLE NGE'\n\nfourth_value = 'fourth'\nfifth_value = 'fifth'\nsixth_value = 'sixth'\n\n# First challenge\n\nf_v = []\n\nfor i in first_value.split():\n if i.isalpha():\n f_v.append(i.capitalize())\n\nfirst_value = \" \" * 7 + \" \".join(f_v)\n\n# Second challenge\n\ns_v = []\n\nfor i in second_value.split():\n if i.isalpha():\n s_v.append(i)\n\nsecond_value = \" \".join(s_v).capitalize()\n\n# Third challenge\n\nt_v_1 = third_value.replace(\" \", \"\")\nt_v_2 = t_v_1.replace(\"-\", \" \")\nt_v_3 = []\nfor i in t_v_2.split():\n t_v_3.append(i)\nthird_value = \" \" * 15 + \" \".join(t_v_3).capitalize()\n\n#print(first_value)\n#print(second_value)\n#print(third_value)\n\n# Fourth challenge - use only the print() function (no f-strings)\n\n#print(fourth_value + \"#\" + fifth_value + \"#\" + sixth_value)\n\n# Fifth challenge - use only a single print() function. Create tabs and new lines using f-strings.\n\n#print(\" \" * 8 + fourth_value + \"\\n\" + \" \" * 8 + fifth_value + \"\\n\" + \" \" * 8 + sixth_value)\n\n\n# CHALLENGE - Perform mathematical operations on numeric data in Python - Calculator\n\ndef calculator(f_num, oper, s_num):\n operators = \"+-**/%\"\n if not f_num.isnumeric() or not s_num.isnumeric():\n return \"Please input a number.\"\n elif oper not in operators:\n return \"Please enter one of the '+-*/**&' operators\"\n else:\n if oper == \"+\":\n return f\"Sum of {f_num} {oper} {s_num} equals {int(f_num) + int(s_num)}\"\n elif oper == \"-\":\n return f\"Difference of {f_num} {oper} {s_num} equals {int(f_num) - int(s_num)}\"\n elif oper == \"*\":\n return f\"Product of {f_num} {oper} {s_num} equals {int(f_num) * int(s_num)}\"\n elif oper == \"**\":\n return f\"Exponent of {f_num} {oper} {s_num} equals {int(f_num) ** int(s_num)}\"\n elif oper == \"%\":\n return f\"Modulus of {f_num} {oper} {s_num} equals {int(f_num) % int(s_num)}\"\n else:\n if oper == \"/\" and s_num == \"0\":\n return \"Division by 0 is not possible\"\n else:\n if int(f_num) % int(s_num) == 0:\n return f\"Quotient of {f_num} {oper} {s_num} equals {int(f_num) // int(s_num)}\"\n else:\n return f\"Quotient of {f_num} {oper} {s_num} equals {int(f_num) / int(s_num)}\"\n\n# first_number = input(\"First number? \")\n# operation = input(\"Operation? \")\n# second_number = input(\"Second number? \")\n\n# print(calculator(first_number, operation, second_number))\n\n\n# Challenge - Iterate through code blocks by using the while statement - Guess a number\n\nimport random\n\ndef guess_a_number():\n number = random.randint(1, 5)\n count = 1\n n = int(input(\"Guess a number between 1 and 5: \"))\n while n != number:\n count += 1\n n = int(input(\"Guess a number between 1 and 5: \"))\n return f\"You guessed it in {count} tries!\"\n\n#print(guess_a_number())\n\n\n# Challenge - Iterate through code blocks by using the while statement - Improved number guessing\n\nimport random\n\ndef imroved_number_guessing():\n number = str(random.randint(1, 10))\n n = \"0\"\n count = 1\n print(\"Guess a number between 1 and 10: \")\n while n != number:\n n = input(f\"Enter guess #{count}: \")\n if n.isdigit():\n if int(n) < int(number):\n print(\"Your guess is too low, try again!\")\n elif int(n) > int(number):\n print(\"Your guess is too high, try again!\")\n elif int(n) == int(number):\n return f\"You guessed it in {count} tries!\"\n else:\n print(\"Numbers only, please!\")\n count += 1\n \n#print(imroved_number_guessing())\n\n\n# CHALLENGE - Manage a sequence of data by using Python lists - Deal a deck of cards\n\nimport random\n\ndef deck_of_cards():\n suits = [\"Hearts\", \"Spades\", \"Clubs\", \"Diamonds\"]\n ranks = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\", \"Ace\"]\n cards_52 = []\n for suit in suits:\n for rank in ranks:\n cards_52.append(f'{rank} of {suit}')\n return cards_52\n\ndef player_hand():\n random_five = []\n for i in range(5):\n x = random.randint(0, 51)\n random_five.append(deck_of_cards()[x])\n return random_five\n\ndef play():\n player = player_hand()\n cards = deck_of_cards()\n\n print(f\"There are {len(cards)} cards in the deck.\")\n print(\"Dealing ...\")\n\n for i in player:\n if i in cards:\n cards.remove(i)\n \n print(f\"There are {len(cards)} cards in the deck.\")\n print(\"Player has the following cards in their hand:\")\n print(player)\n\n#play()\n\n\n# CHALLENGE - Create reusable functionality with functions in Python - Fill in the missing functions\n\nimport processor # create a processor.py file first\n\nmy_list = [5, 'Dan', '4', 7, 'Steve', 'Amy', 'Rhonda', 4, '9', 'Jill', 7, 'Kim']\nmy_bad_list = 5\n\nnumbers = processor.process_numbers(my_list)\nprint(numbers)\n\nnames = processor.process_names(my_list)\nprint(names)\n\nnumbers = processor.process_numbers(my_bad_list)\nprint(numbers)\n\nnames = processor.process_names(my_bad_list)\nprint(names)","repo_name":"valeriybercha/py-test-exercises","sub_path":"msft-learn/python-first-steps.py","file_name":"python-first-steps.py","file_ext":"py","file_size_in_byte":5625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"28401920539","text":"# on server: 'screen' ,then start script\n# use 'strg+a d' to return to terminal\n# use 'screen -r' to return to screen\nimport numpy as np\nimport json\nimport os\nimport math\n\nfrom keras.models import model_from_json\nos.environ['CUDA_VISIBLE_DEVICES']='1'\n\nimport preprocess_data as ppd\nimport train_slices as ts\n\nfrom tqdm import tqdm\n##########################################\npath='models/'\n# rnn parameters\nhidden_size = 100 \nbatch_size = 100 \nepochs = 25\n\nsize=10000\n\n#glove embedding parameters\nglove_dir = '../glove/glove.6B.100d.txt'\nembedding_dim = 100\n############################################\n#open SQuAD-dataset and extract the relevant data from the json-file\n#to an easier readable/accessible dictionary\nwith open('SQuAD/train-v2.0.json') as data_file:\n train=json.load(data_file)\ntrain_qid=[]\ntrain_context=[]\ntrain_question=[]\ntrain_answer=[]\ntrain_new={'context':train_context,'question':train_question,'answer':train_answer,'qid':train_qid}\nfor j,data in enumerate(train['data']):\n for i,paragraph in enumerate(data['paragraphs']):\n context=paragraph['context']\n for qas in paragraph['qas']:\n #create a dataset with only the answerable questions\n #add a bos and eos token to the target\n if (qas['is_impossible']==False):\n c=qas['answers'][0]['text'].lower()\n \n train_new['qid'].append(qas['id'])\n train_new['context'].append(context.lower())\n train_new['question'].append(qas['question'].lower())\n train_new['answer'].append('START_ '+c+' _END')\n else:\n train_new['qid'].append(qas['id'])\n train_new['context'].append(context.lower())\n train_new['question'].append(qas['question'].lower())\n train_new['answer'].append('START_ '+str(qas['answers'])+' _END')\n################################################################\ndata_info=ppd.get_data_info([train_new['context'],\n train_new['question'],\n train_new['answer']])\n\n#get glove embeddings\nprint('getting the glove embeddings')\nembeddings_index = {}\nf = open(glove_dir)\nfor line in tqdm(f):\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\nf.close()\nprint('Found %s word vectors.' % len(embeddings_index))\n\n#extract the glove-embedding to a matrix\ncontext_embedding_matrix = np.zeros((data_info['len_context_vocab'], embedding_dim))\nfor word, i in data_info['context_token_to_int'].items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # words not found in embedding index will be all-zeros.\n context_embedding_matrix[i] = embedding_vector\n\nquestion_embedding_matrix = np.zeros((data_info['len_question_vocab'], embedding_dim))\nfor word, i in data_info['question_token_to_int'].items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # words not found in embedding index will be all-zeros.\n question_embedding_matrix[i] = embedding_vector\n\nanswer_embedding_matrix = np.zeros((data_info['len_answer_vocab'], embedding_dim))\nfor word, i in data_info['answer_token_to_int'].items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # words not found in embedding index will be all-zeros.\n answer_embedding_matrix[i] = embedding_vector\n############################################################\n# train model\nfor slice_size in range(10,math.ceil(len(train_new['context'])/size)):\n ts.train_slices([train_new['context'],train_new['question'],train_new['answer']],\n data_info,\n [context_embedding_matrix,question_embedding_matrix,answer_embedding_matrix],\n hidden_size,\n embedding_dim,\n batch_size,\n epochs,\n slice_size,\n size,\n path)\n######################################################################\n# load the trained encoder and decoder model\nprint('start inference')\nwith open(path+'encoder_model.json', 'r') as encoder_json_file:\n loaded_model_json = encoder_json_file.read()\n encoder_model = model_from_json(loaded_model_json)\nencoder_model.load_weights(path+'encoder_model.h5')\nencoder_json_file.close()\n \nwith open(path+'decoder_model.json', 'r') as decoder_json_file:\n loaded_model_json = decoder_json_file.read()\n decoder_model = model_from_json(loaded_model_json)\ndecoder_model.load_weights(path+'decoder_model.h5')\ndecoder_json_file.close()\n\n# answer question\nqid_to_answer_dict={}\nfor slice_size in range(math.ceil(len(train_new['context'])/size)):\n print('inference on part %s of the dataset' % slice_size)\n input_data=ppd.process_data([train_new['context'][size*slice_size:size*(slice_size+1)],\n train_new['question'][size*slice_size:size*(slice_size+1)],\n train_new['answer'][size*slice_size:size*(slice_size+1)]]\n ,data_info)\n for seq_index in tqdm(range(len(train_new['context'][size*slice_size:size*(slice_size+1)]))):\n decoded_sentence = ppd.decode_sequence(input_data['encoder_input']['context_encoder_input'][seq_index:seq_index+1],\n input_data['encoder_input']['question_encoder_input'][seq_index:seq_index+1],\n data_info['answer_token_to_int'],\n data_info['answer_int_to_token'],\n encoder_model,\n decoder_model)\n qid_to_answer_dict[train_new['qid'][seq_index+(slice_size*size)]]=decoded_sentence\n# write the answers to a .json-file\nprint('write answer to json')\nwith open(path+'answers.json', 'w') as json_file:\n json.dump(qid_to_answer_dict, json_file)\njson_file.close()\n","repo_name":"JacobLoe/QA_project","sub_path":"baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":6132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"70968774979","text":"import os\nimport sys\nimport urllib3\nimport stat\nimport time\nimport datetime\nimport traceback\nimport requests\n\n# Find module path\nMODULE_PATH = os.path.dirname(os.path.realpath(__file__))\n# Find ROOT folder\nROOT = os.path.split(MODULE_PATH)[0]\n\n# Import Custom Libraries\ntry:\n # Frozen Application Method\n from . import query_shapefile_at_point\n from .utilities import JLog\nexcept Exception:\n import query_shapefile_at_point\n # Reverse compatibility step - Add utilities folder to path directly\n PYTHON_SCRIPTS_FOLDER = os.path.join(ROOT, 'Python Scripts')\n TEST = os.path.exists(PYTHON_SCRIPTS_FOLDER)\n if TEST:\n UTILITIES_FOLDER = os.path.join(PYTHON_SCRIPTS_FOLDER, 'utilities')\n sys.path.append(UTILITIES_FOLDER)\n else:\n ARC_FOLDER = os.path.join(ROOT, 'arc')\n UTILITIES_FOLDER = os.path.join(ARC_FOLDER, 'utilities')\n sys.path.append(UTILITIES_FOLDER)\n import JLog\n\nlog = JLog.PrintLog()\n\n# Find module path\nMODULE_FOLDER = os.path.dirname(os.path.realpath(__file__))\n# Find ROOT folder\nROOT_FOLDER = os.path.split(MODULE_FOLDER)[0]\n# Find clim_div folder\nGIS_FOLDER = os.path.join(ROOT_FOLDER, 'GIS')\nCLIM_DIV_FOLDER = os.path.join(GIS_FOLDER, 'climdiv')\n\n\ndef delete_read_only(file_path):\n \"\"\"Ensures Windows Read-Only status does not interrupt os.remove function\"\"\"\n try:\n os.remove(file_path)\n except Exception:\n try:\n os.chmod(file_path, stat.S_IWRITE)\n os.remove(file_path)\n except Exception:\n pass\n\ndef sizeof_fmt(num, suffix='B'):\n for unit in [' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:\n if abs(num) < 1024.0:\n return \"{:6.2f} {}{}\".format(num, unit, suffix)\n num /= 1024.0\n return \"{:6.2f} {}{}\".format(num, 'Y', suffix)\n\ndef ensure_current_pdsidv_file():\n \"\"\"Checks that the newest procdate.txt corresponds with the current pdsidv file\"\"\"\n download = False\n # Ensures CLIM_DIV_FOLDER exists\n try:\n os.makedirs(CLIM_DIV_FOLDER)\n except Exception:\n pass\n base_url = 'https://www1.ncdc.noaa.gov/pub/data/cirs/climdiv'\n proc_date_url = '{}/procdate.txt'.format(base_url)\n # Try to avoid checking the server, if possible (New file published on 4th of the month)\n check_server = True\n log.Wrap(\" Checking for this month's PDSI file on local drive...\")\n today = datetime.datetime.today()\n this_month_proc_date = today.strftime('%Y%m04')\n this_month_file_name = 'climdiv-pdsidv-v1.0.0-{}'.format(this_month_proc_date)\n current_file_path = os.path.join(CLIM_DIV_FOLDER, this_month_file_name)\n if os.path.exists(current_file_path) is True:\n log.Wrap(' Local PDSI file found. Testing file...')\n pdsidv_file_size = os.path.getsize(current_file_path)\n if not pdsidv_file_size < 4415776:\n log.Wrap(' Test passed.')\n check_server = False\n else:\n log.Wrap(' Local PDSI file corrupt.')\n log.Wrap(' Deleting local file...')\n delete_read_only(current_file_path)\n check_server = True\n else:\n log.Wrap(\" This month's PDSI file not found on local drive\")\n if check_server is True:\n # Query ProcDate\n log.Wrap(' Querying the name and date of the latest PDSI file...')\n # urllib3\n http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED')\n response = http.request('GET', proc_date_url)\n proc_date = str(response.data.split(b\"\\n\")[0], 'utf-8')\n current_file_name = 'climdiv-pdsidv-v1.0.0-{}'.format(str(proc_date))\n current_file_path = os.path.join(CLIM_DIV_FOLDER, current_file_name)\n log.Wrap(' Latest file = {}'.format(current_file_name))\n log.Wrap(' Checking for PDSI file on local drive...')\n if os.path.exists(current_file_path) is False:\n log.Wrap(' Local PDSI file not found.')\n download = True\n else:\n log.Wrap(' Local PDSI file found. Testing file...')\n pdsidv_file_size = os.path.getsize(current_file_path)\n if pdsidv_file_size < 4415776:\n log.Wrap(' Local PDSI file corrupt.')\n log.Wrap(' Deleting local file...')\n delete_read_only(current_file_path)\n download = True\n else:\n log.Wrap(' Test passed.')\n if download is True:\n # Download Latest Dataset\n current_file_url = '{}/{}'.format(base_url, current_file_name)\n log.Wrap(' Connecting to latest PDSI file on server...')\n # Streaming with requests module\n num_bytes = 0\n count = 0\n with requests.get(current_file_url, stream=True) as r:\n r.raise_for_status()\n log.Wrap(' Writing PDSI file to local drive...')\n with open(current_file_path, 'wb') as f:\n for chunk in r.iter_content(chunk_size=8192): \n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n num_bytes += 8192\n count += 1\n if count > 25:\n formatted_bytes = sizeof_fmt(num_bytes)\n log.print_status_message(' Downloading file... ({} bytes)'.format(formatted_bytes))\n count = 0\n sys.stdout.flush()\n time.sleep(.1)\n # Clear out any old versions of the pdsidv file\n log.Wrap(' Searching for extraneous PDSI files on local drive...')\n for root, directories, file_names in os.walk(CLIM_DIV_FOLDER):\n for file_name in file_names:\n if 'pdsidv' in file_name:\n if not proc_date in file_name:\n log.Wrap('Deleting {}...'.format(file_name))\n delete_path = os.path.join(root, file_name)\n delete_read_only(delete_path)\n return current_file_path\n\ndef get_clim_div(lat, lon):\n \"\"\"Finds the NOAA Climate Division associated with a given Lat and Lon\"\"\"\n clim_div_shapefile = os.path.join(CLIM_DIV_FOLDER, 'GIS.OFFICIAL_CLIM_DIVISIONS.shp')\n feature_attribute_to_query = \"CLIMDIV\"\n clim_div = query_shapefile_at_point.check(lat=lat,\n lon=lon,\n shapefile=clim_div_shapefile,\n field_name=feature_attribute_to_query)\n if len(clim_div) < 4:\n clim_div = '0{}'.format(clim_div)\n return clim_div\n\ndef get_pdsidv(lat, lon, year, month, pdsidv_file):\n \"\"\"Queries downloaded Palmer Drought Severity Index value for given lat, lon, year, and month\"\"\"\n log.print_section('PDSI - Palmer Drought Severity Index')\n log.Wrap('Querying the Palmer Drought Severity Index...')\n monthly_values = []\n values_with_classes = []\n lightgrn = (0.5, 0.8, 0.5)\n lightblu = (0.4, 0.5, 0.8)\n lightred = (0.8, 0.5, 0.5)\n white = (1, 1, 1)\n try:\n clim_div = get_clim_div(lat, lon)\n if pdsidv_file is None:\n pdsidv_file = ensure_current_pdsidv_file()\n line_identifier = '{}05{}'.format(clim_div, year)\n log.Wrap(' Opening PDSI file to collect monthly values...')\n for line in open(pdsidv_file):\n if line_identifier in line:\n monthly_values.append(line[11:17].replace(\" \", \"\"))\n monthly_values.append(line[18:24].replace(\" \", \"\"))\n monthly_values.append(line[25:31].replace(\" \", \"\"))\n monthly_values.append(line[32:38].replace(\" \", \"\"))\n monthly_values.append(line[39:45].replace(\" \", \"\"))\n monthly_values.append(line[46:52].replace(\" \", \"\"))\n monthly_values.append(line[53:59].replace(\" \", \"\"))\n monthly_values.append(line[60:66].replace(\" \", \"\"))\n monthly_values.append(line[67:73].replace(\" \", \"\"))\n monthly_values.append(line[74:80].replace(\" \", \"\"))\n monthly_values.append(line[81:87].replace(\" \", \"\"))\n monthly_values.append(line[88:94].replace(\" \", \"\"))\n if not monthly_values:\n log.Wrap(' Required monthly values not found in PDSI file.')\n # Test if this year's file is not yet available (Government Shutdown Workaround)\n pdsi_file_year = int(pdsidv_file[-8:-4])\n if pdsi_file_year < int(year):\n log.Wrap(' NOAA server has yet to publish the most up-to-date file. PDSI Unavailable.')\n else:\n log.Wrap(' PDSI file assumed corrupt. Deleting...')\n delete_read_only(pdsidv_file)\n output = [-99.99, 'Not available', white] + [pdsidv_file]\n else:\n for value in monthly_values:\n value_num = float(value)\n if value_num == -99.99:\n classification = 'Not available'\n shading = white\n elif value_num > 4:\n classification = 'Extreme wetness'\n shading = white\n elif value_num > 2.99:\n classification = 'Severe wetness'\n shading = white\n elif value_num > 1.99:\n classification = 'Moderate wetness'\n shading = white\n elif value_num > 0.99:\n classification = 'Mild wetness'\n shading = white\n elif value_num > 0.49:\n classification = 'Incipient wetness'\n shading = white\n elif value_num > -0.51:\n classification = 'Normal'\n shading = white\n elif value_num > -1.01:\n classification = 'Incipient drought'\n shading = lightred\n elif value_num > -2.01:\n classification = 'Mild drought'\n shading = lightred\n elif value_num > -3.01:\n classification = 'Moderate drought'\n shading = lightred\n elif value_num > -4.01:\n classification = 'Severe drought'\n shading = lightred\n elif value_num < -4:\n classification = 'Extreme drought'\n shading = lightred\n values_with_classes.append([value_num, classification, shading])\n output = values_with_classes[int(month)-1] + [pdsidv_file]\n if output[0] == -99.99:\n output = values_with_classes[int(month)-2] + [pdsidv_file]\n month = int(month) - 1\n if month < 1:\n month = 12\n year = int(year) - 1\n output[1] = \"{} ({}-{:02d})\".format(output[1], year, month)\n log.Wrap(' PDSI Value = {} - {}'.format(output[0], output[1]))\n except Exception:\n log.Wrap(' #---PDSI Not Available---#')\n log.Wrap(traceback.format_exc())\n log.Wrap(' #---PDSI Not Available---#')\n output = [-99.99, 'Not available', white, pdsidv_file]\n log.print_separator_line()\n log.Write('')\n return output\n\nif __name__ == '__main__':\n palmer_value, palmer_class, palmer_color, pdsidv_file = get_pdsidv(lat=38.2753586,\n lon=-121.8237463,\n year='2019',\n month='6',\n pdsidv_file=None)\n print('palmer_value={}'.format(palmer_value))\n print('palmer_class={}'.format(palmer_class))\n print('palmer_color={}'.format(palmer_color))\n print('pdsidv_file={}'.format(pdsidv_file))\n","repo_name":"jDeters-USACE/Antecedent-Precipitation-Tool","sub_path":"arc/query_climdiv.py","file_name":"query_climdiv.py","file_ext":"py","file_size_in_byte":12072,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"80"} +{"seq_id":"24319514663","text":"\nfrom Game import *\n\ndef value(hand):\n has_ace=False\n val=0\n for card in hand:\n if card.rank==1:\n has_ace=True\n \n if card.rank>10:\n val+=10\n else:\n val+=card.rank\n \n if has_ace and val+10<21:\n val+=10\n \n return val\n\n\n\ndef play(agents,number_of_decks=1,\n number_of_games=1,display=True):\n\n all_scores=[]\n\n for agent in agents:\n agent.score=0\n\n for game in range(number_of_games): \n \n deck=makedeck(number_of_decks,shuffle=True)\n hands=[]\n # deal two for every agent\n for agent in agents:\n agent.hand=deal(deck,2)\n hands.append(agent.hand)\n \n for agent in agents:\n # shown is all of the cards for all agents, \n # except the first card\n shown={}\n for agent2 in agents:\n shown[agent2.name]=agent2.hand[1:]\n\n hand=agent.hand\n \n if display:\n print(agent.name,\"'s move\")\n print(\"\\tShown is \",shown)\n print(\"\\tYour hand is:\",hand)\n \n while True: # keep going until stay or bust\n move=agent.move(hand,shown,agent)\n if display:\n print(\"\\t Move: \",move)\n if move=='s':\n break\n agent.hand.extend(deal(deck))\n\n if display:\n print(agent.name)\n print(\"\\tShown is \",shown)\n print(\"\\tYour hand is:\",hand)\n\n if value(agent.hand)>21:\n if display:\n print(\"\\tBust!\")\n break\n\n if display:\n print(\"Results\")\n for agent in agents:\n print(agent.name)\n print(\"\\t\",agent.hand)\n print(\"\\t\",value(agent.hand))\n if value(agent.hand)>21:\n print(\"\\t\\tBust!\")\n \n \n winners=[]\n max_so_far=-1\n for agent in agents:\n score=value(agent.hand)\n if score>21: # busting doesn't win\n continue\n if score>max_so_far:\n winners=[agent]\n max_so_far=score\n elif score==max_so_far:\n winners.append(agent)\n max_so_far=score\n else:\n pass\n \n # dealer wins in a tie\n if dealer_agent in winners:\n winners=[dealer_agent]\n\n if display:\n print(\"Winners:\")\n for agent in winners:\n print(\"\\t\",agent.name)\n \n for agent in winners:\n agent.score+=1\n\n if display:\n print(\"=================\")\n \n return [agent.score for agent in agents]\n \ndef dealer_move(hand,shown,info=None):\n\n val=value(hand)\n if val<=16:\n return 'h'\n else:\n return 's'\n\n\ndef human_move(hand,shown,info=None):\n move=input('Hit or stay? ') \n move=move.lower()[0]\n return move \n \ndef random_move(hand,shown,info=None):\n return random.choice(['h','s'])\n \n\nhuman_agent=Agent(human_move)\nhuman_agent.name='Human'\n\ndealer_agent=Agent(dealer_move)\ndealer_agent.name='Dealer'\n\nrandom_agent=Agent(random_move)\nrandom_agent.name='Bob'\n \n\n \nagents=[human_agent,random_agent,dealer_agent]\n\nscores=play(agents,\n number_of_games=2,\n display=True)\n \n","repo_name":"bblais/Game","sub_path":"examples/blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"4534801484","text":"import json\nimport time\nfrom selenium import webdriver\nimport requests\n\ndef test(sub):\n res = requests.get('https://weibo.com',headers = {'Cookie': 'SUB=' + sub}).text\n if 'ggxxding' in res:\n return True\n else:\n return False\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('--disable-gpu')\noptions.add_argument('--headless')\nchrome = webdriver.Chrome(options=options)\nchrome.set_window_size(1920, 1080)\nchrome2 = webdriver.Chrome(options=options)\nchrome2.set_window_size(1920, 1080)\n\nchrome.get('https://weibo.com/login.php')\nchrome2.get('https://weibo.com/login.php')\ntime.sleep(5)\nchrome.find_elements_by_xpath('//a[@action-data=\"type=qrcode\"]')[0].click()\ntime.sleep(2)\nchrome.save_screenshot('screenshots/screenshot.png')\ninput('等待登录')\n\nwith open('cookies.txt', 'r', encoding='utf8') as f:\n Cookies = json.loads(f.read())\nfor cookie in Cookies:\n chrome2.add_cookie(cookie)\nchrome2.refresh()\ntime.sleep(5)\n\nchrome.save_screenshot('screenshots/screenshot.png')\nchrome2.save_screenshot('screenshots/screenshot2.png')\nprint('save screenshot')\n\nsub1 = chrome.get_cookie('SUB')\nsub2 = chrome2.get_cookie('SUB')\n\nwhile (1):\n chrome.refresh()\n time.sleep(10)\n while (chrome.get_cookie('SUB') == None):\n chrome.refresh()\n time.sleep(10)\n print('chrome_1重新刷新')\n sub1_1 = chrome.get_cookie('SUB')\n\n chrome2.refresh()\n time.sleep(10)\n while (chrome2.get_cookie('SUB') == None):\n chrome2.refresh()\n time.sleep(10)\n print('chrome_2重新刷新')\n sub2_2 = chrome2.get_cookie('SUB')\n\n print('sub1 =', sub1['value'])\n print('sub1_1=', sub1_1['value'])\n print('sub1有效:', test(sub1['value']))\n print('sub1_1有效:', test(sub1_1['value']))\n print('sub1相等:', sub1['value'] == sub1_1['value'])\n print('sub2 =', sub2['value'])\n print('sub2_2=', sub2_2['value'])\n print('sub2有效:', test(sub2['value']))\n print('sub2_2有效:', test(sub2_2['value']))\n print('sub2相等:', sub2['value'] == sub2_2['value'])\n sub1 = sub1_1\n sub2 = sub2_2\n time.sleep(1800)\n\n","repo_name":"ggxxding/AI-public-opinion-perception","sub_path":"backend/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"20907322301","text":"import sys\nimport tweepy\nimport csv\nimport time\nimport constants\n\n\nconsumer_key = constants.API_KEY\nconsumer_secret = constants.API_SECRET\naccess_token = constants.ACCESS_TOKEN\naccess_token_secret = constants.ACCESS_TOKEN_SECRET\n\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\n\n\ndef twitter_stream_listener(file_name,\n filter_track,\n follow=None,\n locations=None,\n languages=None,\n time_limit=20):\n class CustomStreamListener(tweepy.StreamListener):\n def __init__(self, time_limit):\n self.start_time = time.time()\n self.limit = time_limit\n # self.saveFile = open('abcd.json', 'a')\n super(CustomStreamListener, self).__init__()\n def on_status(self, status):\n if (time.time() - self.start_time) < self.limit:\n # print(\".\", end=\" \")\n # Writing status data\n with open(file_name, 'a') as f:\n writer = csv.writer(f)\n writer.writerow([\n status.author.screen_name, status.created_at,\n status.text\n ])\n else:\n print(\"\\n\\n[INFO] Closing file and ending streaming\")\n return False\n\n def on_error(self, status_code):\n if status_code == 420:\n print('Encountered error code 420. Disconnecting the stream')\n # returning False in on_data disconnects the stream\n return False\n else:\n print('Encountered error with status code: {}'.format(\n status_code))\n return True # Don't kill the stream\n\n def on_timeout(self):\n print('Timeout...')\n return True # Don't kill the stream\n # Writing csv titles\n print(\n '\\n[INFO] Open file: [{}] and starting {} seconds of streaming for {}\\n'\n .format(file_name, time_limit, filter_track))\n with open(file_name, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['author', 'date', 'text'])\n streamingAPI = tweepy.streaming.Stream(\n auth, CustomStreamListener(time_limit=time_limit))\n streamingAPI.filter(\n track=filter_track,\n follow=follow,\n locations=locations,\n languages=languages,\n )\n f.close()\n\n\nfilter_track = ['Iranprotest']\nfile_name = 'Iran_protest.csv'\ntwitter_stream_listener (file_name, filter_track, time_limit=60)\n\n","repo_name":"EhsanArabnezhad/social-media","sub_path":"stream-tweet.py","file_name":"stream-tweet.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"22343728494","text":"import cv2\nimport pytesseract\n\n# Set the path to the Tesseract executable\npytesseract.pytesseract.tesseract_cmd = r\"C:\\Users\\Rahul\\Tesseract\\tesseract.exe\"\n\n# Function to extract text from an image\ndef extract_text_from_image(image, lang='eng'):\n # Convert the image to grayscale\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # Apply image preprocessing techniques (adjust according to your needs)\n gray = cv2.medianBlur(gray, 3) # Apply median blur to reduce noise\n gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n # Use Pytesseract to extract text from the image\n text = pytesseract.image_to_string(gray, lang=lang)\n return text\n\n# Function to process an image\ndef process_image(file_path):\n # Load the image from file path\n image = cv2.imread(file_path)\n\n if image is not None:\n # Extract text from the image\n text = extract_text_from_image(image, lang='eng')\n # Print the extracted text\n if text.strip():\n print(\"Image Text:\")\n print(text)\n else:\n print(\"No text found in the image.\")\n else:\n print(\"Failed to load the image.\")\n\n# Prompt the user for the image file path\nfile_path = input(\"Enter the path of the image file: \")\n\n# Process the image file\nprocess_image(file_path)\n","repo_name":"RahulBoyidapu/Text_extraction_from_images","sub_path":"Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"70805842179","text":"import json\nimport requests\nfrom secret import API_geo_google\nimport sqlite3 as sqlite\n\ndef get_count():\n ## count the the number of occurance of each skills\n f = open('people_cache.json', 'r')\n dic = json.load(f)\n f.close()\n skills_all = {}\n for comapny in dic:\n current_company = dic[comapny]\n for people in current_company:\n people_current = current_company[people]\n skills = people_current['skills']\n for sk in skills:\n if sk in skills_all:\n skills_all[sk] += 1\n else:\n skills_all[sk] = 1\n return skills_all\n\ndef create_db():\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n statement = '''\n DROP TABLE IF EXISTS 'People';\n '''\n cur.execute(statement)\n\n statement = '''\n DROP TABLE IF EXISTS 'Company';\n '''\n cur.execute(statement)\n statement = '''\n DROP TABLE IF EXISTS 'Skill';\n '''\n cur.execute(statement)\n\n statement = '''\n DROP TABLE IF EXISTS 'Place';\n '''\n cur.execute(statement)\n conn.commit()\n conn.close()\n\ndef skill_db():\n # Connect to big10 database\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n statement = '''\n CREATE TABLE 'Skill' (\n 'Id' INTEGER PRIMARY KEY AUTOINCREMENT,\n 'Name' TEXT NOT NULL,\n 'Frequency' Integer\n );\n '''\n cur.execute(statement)\n conn.commit()\n conn.close()\n\ndef people_db():\n # Connect to big10 database\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n statement = '''\n CREATE TABLE 'People' (\n 'Id' INTEGER PRIMARY KEY AUTOINCREMENT,\n 'Name' TEXT NOT NULL,\n 'Title' TEXT,\n 'Location' TEXT,\n 'Skills' TEXT,\n 'Recent_school' TEXT, \n 'Company' TEXT, \n CompanyId Integer,\n FOREIGN KEY (CompanyId) REFERENCES Company(Id)\n );\n '''\n cur.execute(statement)\n conn.commit()\n conn.close()\n\ndef company_db():\n # Connect to big10 database\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n statement = '''\n CREATE TABLE 'Company' (\n 'Id' INTEGER PRIMARY KEY AUTOINCREMENT,\n 'Name' TEXT NOT NULL,\n 'Website' TEXT,\n 'Location' TEXT,\n 'Found_year' TEXT,\n 'Specialties' TEXT \n );\n '''\n cur.execute(statement)\n conn.commit()\n conn.close()\ndef place_db():\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n statement = '''\n CREATE TABLE 'Place' (\n 'Id' INTEGER PRIMARY KEY AUTOINCREMENT,\n 'Place' TEXT NOT NULL,\n 'Lat' TEXT,\n 'Lng' TEXT\n );\n '''\n\n cur.execute(statement)\n conn.commit()\n conn.close()\n\ndef insert_allData():\n company_db()\n people_db()\n place_db()\n skill_db()\n ##Insert Company id_CompanyLocationId = cur.execute('SELECT Id FROM Countries where EnglishName = ?', (row[5],))\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n file_comapny = open('company_cache.json', 'r')\n file_json = json.load(file_comapny)\n for company in file_json:\n cur_company = file_json[company]\n name = cur_company['name'].lower()\n website = cur_company['website']\n location = cur_company['location']\n found_year = cur_company['found_year']\n specialties = cur_company['specialties']\n statement = '''\n INSERT INTO 'Company' (Name, Website, Location,Found_year,Specialties) VALUES (?, ?, ?,?,?)\n '''\n cur.execute(statement, (name, website,location, found_year, specialties,))\n conn.commit()\n ##Insert People\n file_people = open('people_cache.json', 'r')\n file_json = json.load(file_people)\n for company in file_json:\n cur_company = file_json[company]\n CompanyId = cur.execute('SELECT Id FROM Company where name = ?', (company.lower(),)).fetchall()[0][0]\n # print(CompanyId[0][0])\n for url_people in cur_company:\n people = cur_company[url_people]\n name = people['name']\n title = people['title']\n location = people['location']\n skills = people['skills']\n school_recent = people['school_recent']\n statement = '''\n INSERT INTO 'People' (Name, Title, Location,Skills,Recent_school, company, CompanyId) VALUES (?, ?, ?,?,?, ?,?)\n '''\n cur.execute(statement, (name, title,location, ' '.join(skills), school_recent,company, CompanyId,))\n conn.commit()\n\n ##Insert Skill\n skill_count = get_count()\n for skill in skill_count:\n count_cur = skill_count[skill]\n statement = '''\n INSERT INTO 'Skill' (Name, Frequency) VALUES (?,?)\n '''\n cur.execute(statement, (skill,count_cur,))\n conn.commit()\n ##Insert Places\n statement='''\n SELECT distinct Location FROM People\n '''\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n places = cur.execute(statement).fetchall()\n for cur_place in places:\n url = 'https://maps.googleapis.com/maps/api/geocode/json?address={}r&key={}'.format(cur_place[0], API_geo_google)\n res = requests.get(url).json()\n location = res['results'][0]['geometry']['location']\n latitude = location['lat']\n longtitude = location['lng']\n cur_statement = '''\n INSERT INTO 'Place' (Place, Lat, Lng) VALUES (?,?,?)\n '''\n cur.execute(cur_statement, (cur_place[0],latitude, longtitude))\n conn.commit()\n conn.close()\n file_people.close()\n\ndef insert_company(current_company):\n if current_company == None:\n return\n conn = sqlite.connect('linkedin.sqlite')\n cur = conn.cursor()\n indb_if = cur.execute('select Name from Company where Name = ?', (current_company.name,)).fetchall()\n\n if len(indb_if) >0:\n print('Already has the company in DB...')\n else:\n statement = '''\n INSERT INTO 'Company' (Name, Website, Location,Found_year,Specialties) VALUES (?, ?, ?,?,?)\n '''\n cur.execute(statement, (current_company.name.lower(), current_company.web,current_company.location, current_company.found_year, current_company.specialties,))\n conn.commit()\n conn.close()\n\n\ndef rebuild_data():\n create_db()\n print(\"Rebuilding the Linkedin Database...\")\n insert_allData()\n print(\"done!\")\n","repo_name":"xqinglin/linkedin_scrape","sub_path":"setup_db.py","file_name":"setup_db.py","file_ext":"py","file_size_in_byte":6988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"14297392517","text":"import os\nimport os.path\nimport re\nimport tc_classes\n\n\nclass Report:\n \"\"\"\n Класс, возвращаемый функцией analize,\n содержит поля fullsize, общий объем возвращаемых файлов в B,\n files, списко файлов в виде классов Document из tc_classes\n \"\"\"\n def __init__(self):\n self.fullsize = 0\n self.files = []\n\n\ndef analize(dbpath, dbtype):\n \"\"\"\n Функция анализа папки на переданный тип данных\n :param dbpath: путь папки для анализа\n :param dbtype: тип искомых данных\n :return: объект класса Report\n \"\"\"\n if dbtype == 'dos':\n mask = re.compile('\\.[\\d]{3}')\n elif dbtype == 'xml':\n mask = re.compile('\\.xml')\n elif dbtype == 'MDB':\n mask = re.compile('\\.json')\n\n objs = os.listdir(dbpath)\n dirs = list(filter(lambda x: os.path.isdir(os.path.join(dbpath, x)), objs))\n files = list(map(lambda f: tc_classes.Document(f, dbpath, dbtype), filter(lambda x: mask.search(x), objs)))\n\n for d in dirs:\n objs = os.listdir(os.path.join(dbpath, d))\n dirs.extend(map(lambda xx: os.path.join(d, xx),\n filter(lambda x: os.path.isdir(os.path.join(dbpath, d, x)), objs)))\n files.extend(map(lambda f: tc_classes.Document(f, os.path.join(dbpath, d), dbtype),\n filter(lambda x: mask.search(x), objs)))\n\n r = Report\n r.fullsize = sum(map(lambda x: x.size, files))\n r.files = files\n\n return r\n","repo_name":"DyDyktiv/texcom","sub_path":"tc_analize.py","file_name":"tc_analize.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"14514416426","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom setuptools import setup\nimport re\n\n# load version form _version.py\nVERSIONFILE = \"lhdpy/_version.py\"\nverstrline = open(VERSIONFILE, \"rt\").read()\nVSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\nmo = re.search(VSRE, verstrline, re.M)\nif mo:\n verstr = mo.group(1)\nelse:\n raise RuntimeError(\"Unable to find version string in %s.\" % (VERSIONFILE,))\n\n# module\n\nsetup(\n name=\"lhdpy\",\n version=verstr,\n author=\"Keisuke Fujii\",\n author_email=\"fujiisoup@gmail.com\",\n description=(\"Python small library to download LHD data archives.\"),\n license=\"BSD 3-clause\",\n keywords=\"plasma fusion\",\n include_package_data=True,\n ext_modules=[],\n packages=[\"lhdpy\",],\n package_dir={\"lhdpy\": \"lhdpy\"},\n py_modules=[\"lhdpy.__init__\"],\n test_suite=\"tests\",\n install_requires=\"\"\"\n numpy>=1.11\n xarray>=0.10\n \"\"\",\n classifiers=[\n \"License :: OSI Approved :: BSD License\",\n \"Natural Language :: English\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python :: 3.6\",\n \"Topic :: Scientific/Engineering :: Physics\",\n ],\n)\n","repo_name":"fujiisoup/lhdpy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"80"} +{"seq_id":"36449951400","text":"from matplotlib import image\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef get_image():\n primary_img = input(\"Enter directory: \")\n matrix_img = image.imread(primary_img)\n return matrix_img\n\n\ndef create_gray_image(primary_img):\n for i in range(i_index):\n for j in range(j_index):\n if np.any(primary_img[i][j] < 240):\n gray_img[i][j] = (169, 169, 169)\n return gray_img\n\n\ndef create_shear_image(img):\n for i in range(i_index):\n for j in range(j_index):\n shear_i_index = i\n shear_j_index = int(0.2 * i + j)\n shear_img[shear_i_index, shear_j_index] = img[i][j]\n return shear_img\n\n\ndef crate_result_image(img):\n for i in range(i_index):\n for j in range(j_index + offset):\n if j >= j_index:\n result_img[i][j] = img[i][j]\n elif j < j_index:\n if np.any(primary_image[i][j] < 240):\n result_img[i][j] = primary_image[i][j]\n elif np.all(img[i][j] == 169):\n result_img[i][j] = img[i][j]\n return result_img\n\n\nif __name__ == '__main__':\n primary_image = get_image()\n i_index = primary_image.shape[0]\n j_index = primary_image.shape[1]\n offset = int(primary_image.shape[1] * 0.2)\n gray_img = np.full([i_index, j_index, 3], [255, 255, 255])\n shear_img = np.full([i_index, j_index + offset, 3], [255, 255, 255])\n result_img = np.full([i_index, j_index + offset, 3], [255, 255, 255])\n gray_image = create_gray_image(primary_image)\n shear_image = create_shear_image(gray_image)\n result_image = crate_result_image(shear_image)\n plt.imshow(result_image)\n plt.show()\n","repo_name":"arghavansoleymanpour/Projection-Shadows","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"73314059138","text":"import numpy as np\nimport os, sys, ipdb, datetime, click, pickle #tqdm\n\nimport seaborn as sns\nsns.set_context('talk')\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\nWritten by Christopher Hsu\n\nPlot and save figure 2\n\"\"\"\n\n\nsrc_dir = './fig2/data/'\ns = pickle.load(open(os.path.join(src_dir, 'sim_sigs.pkl'),'rb'))\nw = pickle.load(open(os.path.join(src_dir, 'w_react_sigs.pkl'),'rb'))\n\nsigs = s['sigs']\ncosts = s['costs']\nacosts = s['acosts']\nstdev = s['stdev']\nh = s['h']\ndiversity = s['diversity']\npds = s['pds']\n\nsns.set_theme()\nfsz = 32\nplt.rc('font', size=fsz)\nplt.rc('axes', titlesize=fsz)\nplt.rc('axes', labelsize=fsz)\nplt.rc('xtick', labelsize=fsz)\nplt.rc('ytick', labelsize=fsz)\nplt.rc('legend', fontsize=0.7*fsz)\nplt.rc('figure', titlesize=fsz)\nplt.rc('pdf', fonttype=42)\nsns.set_style(\"ticks\", rc={\"axes.grid\":True})\n\n\n## fig 2 left\nfig, ax = plt.subplots(figsize=(8,8))\nax.plot(w['x'],w['qa'],label='$\\sigma_Q=0.1$', linewidth=4.0);\nax.plot(w['x'],pds[10],label='$\\sigma_P=0.05$', linewidth=4.0);\nax.plot(w['x'],pds[27],label='$\\sigma_P=0.13$', linewidth=4.0);\nax.plot(w['x'],pds[-1],label='$\\sigma_P=0.2$', linewidth=4.0);\nplt.legend();\nax.set_xlabel('State (x)')\nax.set_ylabel('Probability')\nplt.tight_layout()\nsns.despine(ax=ax)\n\n\n## fig 2 right\nfig2, ax2 = plt.subplots(figsize=(8,8))\ncolor = 'tab:blue'\nax2.set_xlabel('Cross-Reactivity Bandwidth $\\sigma$')\nax2.scatter(sigs, costs, color=color, label='Empirical Harm')\n\nfor ii in range(len(sigs)):\n minerror = max(costs[ii]-stdev[ii], 0)\n ax2.plot([sigs[ii], sigs[ii]], [costs[ii]+stdev[ii], minerror], marker=\"_\", color=color, alpha=0.5, linewidth=2.0)\nax2.set_ylabel('Empirical Harm', color=color)\nax2.tick_params(axis='y', labelcolor=color)\n\nax3 = ax2.twinx()\ncolor = 'tab:orange'\nax3.plot(sigs, diversity, label='', color=color, linewidth=4.0)\nax3.set_ylabel('Diversity of Defense ($||P_d^*||_0$)', color=color)\nax3.tick_params(axis='y', labelcolor=color)\n\nfig2.tight_layout()\nsns.despine(ax=ax2, right=False)\nsns.despine(ax=ax3, right=False)\n\nsave_dir = './fig2/figures'\nif not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\nfig.savefig(os.path.join(save_dir,'gauss_probs.pdf'),bbox_inches='tight')\nfig2.savefig(os.path.join(save_dir,'gauss_harms.pdf'),bbox_inches='tight')\n\nplt.show()","repo_name":"grasp-lyrl/Model4MAInteractions","sub_path":"src/fig2/fig_gauss.py","file_name":"fig_gauss.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5553232876","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.display , name='index'),\n path('upload/', views.upload_file, name='upload_file'),\n path('register/', views.email_validate, name='register'),\n path('email/', views.email_send, name='email'),\n path('review//',views.display_review, name='review'),\n path('reviews//', views.write_review, name='write_review'),\n path('upload//', views.bookgroup, name='bookgroup'),\n]","repo_name":"PKStuff/Book_Store","sub_path":"webapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"11999185544","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 3 22:15:16 2020\n\n@author: P. M. Harrington\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nimport datetime\n\nimport seq_experiments\nimport seq_programs\nimport daq_programs\nimport analysis\n\nimport wx_programs\nimport keithley2401\n#import hp_E4405B\n\nclass Nop():\n def __init__(self, name):\n self.name = name\n\ndef get_save_path():\n path0 = \"C:\\\\Data\\\\2020\\\\ep_metrology\\\\data\\\\data_200303\"\n time_str = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n save_path = path0 + time_str\n return save_path\n\ndef save_by_pickle(data_in):\n save_path = get_save_path()\n fname = save_path + \".pickle\"\n print(fname)\n \n with open(fname, \"wb\") as open_file:\n pickle.dump(data_in, open_file)\n\n#def make_readme(parameters):\n# paths = parameters.paths\n# \n# paths.readme = paths.parent + \"/\" + \"readme.txt\"\n# if (not os.path.exists(paths.readme)):\n# file = open(paths.readme, \"w\") \n# else:\n# file = open(paths.readme, \"a\")\n# file.write(\"\\n\\n\")\n# \n# p = parameters \n# file.write(\"# \" + p.label + \"\\n\")\n# file.write(p.time_start.strftime(\"%Y%m%d_%H%M%S\"))\n# file.write(\"\\nboundary, {}\".format(p.boundary))\n# file.write(\"\\nN, {}\".format(p.N))\n# file.write(\"\\nJ, {}\".format(p.J))\n# file.close()\n \n \nif __name__ == '__main__':\n pass\n\n# # ramsey & t1decay, ge\n# num_patterns_each = 51\n# sweep_time_ramsey = 2500\n# sweep_time_t1decay = 5000\n# seq.ramsey_ge_t1decay_ge(num_patterns_each, sweep_time_ramsey, sweep_time_t1decay)\n# times_ramsey = np.linspace(0.,sweep_time_ramsey, num_patterns_each)*1e-3\n# times_t1decay = np.linspace(0.,sweep_time_t1decay, num_patterns_each)*1e-3\n# daq_params, rec_readout_vs_pats, p_readout = daq_programs.run_daq(num_patterns=2*num_patterns_each, num_records_per_pattern=500)\n# p_ramsey = p_readout[0][:num_patterns_each]\n# p_t1decay = p_readout[0][num_patterns_each:] \n# popt, _ = analysis.fit_sine_decay(times_ramsey, p_ramsey)\n# fit_t1decay, _ = analysis.fit_exp_decay(times_t1decay, p_t1decay)\n# print(\"\\nT2*: {}\".format(1/popt[0][1]))\n# print(\"T1: {}\".format(1/fit_t1decay[0][1]))\n \n # ramsey & t1decay, ge\n seq = Nop(\"seq\")\n seq.comment = \"ramsey & t1decay, ge\"\n seq.num_patterns_each = 101\n seq.sweep_time_ramsey = 1000\n seq.sweep_time_t1decay = 5000\n seq.num_records_per_pattern = 200\n \n keithley_current = Nop(\"keithley_current\")\n keithley_current.num_steps = 25\n keithley_current.setpoint_mA = np.linspace(7.29, 7.35, keithley_current.num_steps)\n dum = np.full(keithley_current.num_steps, np.nan)\n keithley_current.msmt_mA_start = dum\n keithley_current.msmt_mA_end = dum\n #seq.ramsey_ge_t1decay_ge(num_patterns_each, sweep_time_ramsey, sweep_time_t1decay)\n \n #\n ramsey = Nop(\"ramsey\")\n ramsey.times = np.linspace(0.,seq.sweep_time_ramsey, seq.num_patterns_each)*1e-3\n ramsey.freq = dum.copy()\n ramsey.gamma = dum.copy()\n ramsey.p = []\n \n t1decay = Nop(\"t1decay\")\n t1decay.times = np.linspace(0.,seq.sweep_time_t1decay, seq.num_patterns_each)*1e-3\n t1decay.freq = dum.copy()\n t1decay.gamma = dum.copy()\n t1decay.p = []\n \n #\n daq = Nop(\"daq\")\n for k, bias_val in enumerate(keithley_current.setpoint_mA):\n mA_start, mA_end = keithley2401.set_current(bias_val)\n keithley_current.msmt_mA_start[k] = mA_start\n keithley_current.msmt_mA_end[k] = mA_end\n \n daq.daq_params, daq.rec_readout_vs_pats, daq.p_readout = (\n daq_programs.run_daq(num_patterns=2*seq.num_patterns_each, num_records_per_pattern=seq.num_records_per_pattern))\n ramsey.p.append(daq.p_readout[0][:seq.num_patterns_each])\n t1decay.p.append(daq.p_readout[0][seq.num_patterns_each:])\n \n #\n keithley_current.msmt_mA_end = np.array(keithley_current.msmt_mA_end)\n ramsey.p = np.array(ramsey.p)\n t1decay.p = np.array(t1decay.p)\n \n #\n ramsey.fit= []\n t1decay.fit = []\n for k in range(keithley_current.num_steps):\n #\n popt, perr, _, _ = analysis.fit_sine_decay(ramsey.times, ramsey.p[k])\n ramsey.fit.append(popt)\n #.\n popt, perr, _, _ = analysis.fit_exp_decay(t1decay.times, t1decay.p[k])\n t1decay.fit.append(popt)\n \n #\n ramsey.fit = np.array(ramsey.fit)\n ramsey.freq = ramsey.fit.T[0]\n ramsey.gamma = ramsey.fit.T[1]\n #\n t1decay.fit = np.array(t1decay.fit)\n t1decay.gamma = t1decay.fit.T[1]\n \n# keithley_current.msmt_mA_end = keithley_current.setpoint_mA\n \n plt.figure()\n plt.plot(keithley_current.msmt_mA_end, ramsey.gamma)\n plt.ylabel(\"Ramsey, 1/T2* (1/us)\")\n #\n plt.figure()\n plt.plot(keithley_current.msmt_mA_end, ramsey.freq)\n plt.ylabel(\"Ramsey, frequency (MHz)\")\n #\n plt.figure()\n plt.plot(keithley_current.msmt_mA_end, t1decay.gamma)\n plt.ylabel(\"T1 decay, 1/T1 (1/us)\")\n #\n plt.figure()\n t2s = ramsey.gamma\n t1 = t1decay.gamma\n plt.plot(keithley_current.msmt_mA_end, t2s/(2*t1))\n plt.ylabel(\"t2*/(2t1)\")\n #\n plt.figure()\n t2_pure = 1/(ramsey.gamma - 0.5*t1decay.gamma)\n plt.plot(keithley_current.msmt_mA_end, t2_pure)\n plt.ylabel(\"t2 pure dephasing\")\n \n #\n plt.show()\n \n #\n save_by_pickle((seq, daq, keithley_current, ramsey, t1decay))\n \n# with open(fname, \"rb\") as open_file: \n# x = pickle.load(open_file)\n# print(x)","repo_name":"murchlab/analyzer","sub_path":"instruments/old_python/old/ramsey_t1decay_vs_keithley.py","file_name":"ramsey_t1decay_vs_keithley.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"33040389848","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\nfrom __future__ import division\nimport scipy.io\nimport matplotlib.pyplot as plt\nget_ipython().magic('matplotlib inline')\n\n\n# In[2]:\n\nour_images = scipy.io.loadmat('IMAGES.mat')\nimages = our_images['IMAGES']\n\n\n# In[3]:\n\ndef fakel2norm(m):\n num = np.shape(m)[1]\n total = np.sum(m*m)\n total = total/num\n return total\n \n# In[4]:\n\ndef fakel1norm(m):\n num = np.shape(m)[1]\n mabs = np.abs(m)\n total = np.sum(mabs)\n total = total/num\n return total\n\n# In[5]:\n\ndef energy(I, a, phi, lam):\n recon_error = I - a.dot(phi)\n term1 = fakel2norm(recon_error)\n term2 = lam*fakel1norm(a)\n ans = term1 + term2\n return ans\n\n# In[6]:\n\ndef phigradient(I, a, phi, r, s):\n total = 0\n phit = np.transpose(phi)\n for i in range(np.shape(a)[0]):\n total = total + -2*a[i][r-1]*(I[i][s-1] - np.dot(a[i], phit[s-1]))\n total = total/np.shape(a)[0]\n return total\n\ndef agradient(I, a, phi, r, s, lam):\n total = 0\n phit = np.transpose(phi)\n for i in range(np.shape(a)[0]):\n for j in range(np.shape(phi)[1]):\n total = total + -2*(I[i][j] - np.dot(a[i], phit[j]))*phi[s-1][j]\n total = total/np.shape(a)[0]\n total = total + (lam/np.shape(phi)[0])*np.sign(a[r-1][s-1])\n return total\n\n# In[7]:\n\ndef normalize(m):\n for i in range(np.shape(m)[0]):\n m[i] = np.true_divide(m[i], np.linalg.norm(m[i]))\n return m\n\n\n# In[8]:\n\ndef random_patch(library, width):\n im = library[:,:,np.random.randint(10)]\n x = np.random.randint(np.shape(im)[0] - width)\n y = np.random.randint(np.shape(im)[1] - width)\n patch = im[x:x+width,y:y+width]\n return patch\n\n \n\n\n# In[9]:\n\ndef make_batch(library, num, width):\n I = np.zeros((num, width*width))\n count = 0\n while count < num:\n im = random_patch(library, width)\n im_vec = im.reshape(1, width*width)\n im_vec = np.true_divide(im_vec, np.linalg.norm(im_vec))\n I[count] = im_vec\n count = count + 1\n return I\n\n\n# In[10]:\n\ndef init_phis(num, size):\n phis = np.random.rand(num, size)\n return normalize(phis)\n\n\n# In[4]:\n\nI = make_batch(images, 8, 3)\nphis = init_phis(20, 9)\na = np.random.rand(8, 20)\neps = 1.5\n\n\n# In[8]:\n\nenergy(I, a, phis, 1)\n\n\n# In[9]:\n\nfor time in range(600):\n a = np.random.rand(8, 20)\n I = make_batch(images, 8, 3)\n for ai in range(100):\n for i in range(np.shape(a)[0]):\n for j in range(np.shape(a)[1]):\n a[i][j] = a[i][j] - 0.001*agradient(I, a, phis, i, j, 1)\n for i in range(np.shape(phis)[0]):\n for j in range(np.shape(phis)[1]):\n phis[i][j] = phis[i][j] - 0.001*phigradient(I, a, phis, i, j)\n \n\n\n# In[10]:\n\nenergy(I, a, phis, 1)\n\n\n# In[ ]:\n\n\n\n","repo_name":"AliAlSetri/scoding","sub_path":"spcoding.py","file_name":"spcoding.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"71099915778","text":"import time\nimport helpers\nimport math\n\n# inputFile = open('resources/', 'r')\n\nstart = time.perf_counter()\n\n\ndef fibonachi_to(num):\n if num in [0, 1]:\n return 1\n else:\n return fibonachi_to(num - 1) + fibonachi_to(num - 2)\n\n\nto = 500000\n# 2011026\nfibs = [1, 1]\ncounter = 2\nlll = 500\nten9 = 10 ** 9\ndigits = [str(i) for i in range(1, 10)]\npre_tail = 1\ntail = 1\nfor i in range(2, to):\n counter += 1\n next_fib = sum(fibs)\n new_tail = (tail + pre_tail) % 1000000000\n tail_set = sorted(str(new_tail))\n if tail_set == digits:\n print(\"!!!!!!!\", counter, tail_set, next_fib)\n tip = next_fib // max(1, int(10 ** (math.floor(math.log10(next_fib)) + 1 - 9)))\n tip_set = sorted((str(tip)))\n # str_thing = str(next_fib)\n # tip_set = set(str(str_thing[:9]))\n if tip_set == digits:\n print(\"?????\", counter, tip_set, next_fib)\n print('AMAZING!!!!', counter, next_fib)\n break\n pre_tail, tail = tail, new_tail\n fibs = [fibs[1], next_fib]\n\nprint(time.perf_counter() - start)\n","repo_name":"xpy/Project_euler_python","sub_path":"solved/104.py","file_name":"104.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"33105372270","text":"\"\"\"\nThis script will launch the two nodes that we have written:\nthe joint trajectory publisher and the joint state subscriber.\n\"\"\"\nimport sys\nfrom launch import LaunchDescription\nfrom launch.substitutions import PathJoinSubstitution\nfrom launch_ros.actions import Node\nfrom launch_ros.substitutions import FindPackageShare\nfrom ament_index_python.packages import get_package_share_directory, PackageNotFoundError\n\n\ndef generate_launch_description():\n\n # read values from our self-defined yml file for defining ROS parameters\n config = PathJoinSubstitution(\n [FindPackageShare(\"my_controller\"), \n \"config\", \n \"publisher_config.yaml\"]\n )\n\n # try:\n # get_package_share_directory(\"my_controller\")\n \n # except PackageNotFoundError:\n # print(\n # \"ERROR:\"\n # \"Could not find package 'my_controller'. \"\n # )\n # sys.exit(1)\n \n # NOTE: executable is the name of the entry points defined in `setup.py`\n return LaunchDescription(\n [ \n Node(\n package=\"my_controller\",\n executable=\"joint_controller\", \n name=\"publisher_joint_trajectory_controller\",\n parameters=[config], # tell ROS to set the ROS parameters from our self-defined yml file\n output={\n \"stdout\": \"screen\",\n \"stderr\": \"screen\",\n },\n ),\n Node(\n package=\"my_controller\",\n executable=\"joint_subscriber\", \n name=\"subscriber_joint_state\",\n output={\n \"stdout\": \"screen\",\n \"stderr\": \"screen\",\n },\n ),\n ]\n )","repo_name":"opallch/simple_ur3e_controller","sub_path":"launch/my_controller.launch.py","file_name":"my_controller.launch.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"43576175660","text":"\"\"\"defines project CONSTS for reports templates and final reports directory\"\"\"\nimport os\nimport reports\n\nreports_app_path = os.path.dirname(reports.__file__)\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root\n\nREPORT_TEMPLATES_DIR = os.path.join(reports_app_path, 'templates')\nUNIVERSAL_TEMPLATE_NAME = 'template_universal.docx'\n\nOUTPUT_REPORTS_DIR = os.path.join(ROOT_DIR, '../output_reports')\n","repo_name":"starling-21/report_builder","sub_path":"app/reports/definitions.py","file_name":"definitions.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16843587720","text":"# coding: utf-8\n\nimport logging\n\nimport numpy as np\n\nfrom .result import Result\n\n# set up logging\nLOGGER = logging.getLogger(__name__)\n\n\nclass TXTResult(object):\n def __init__(self, file_name, parser):\n self.file_name = file_name\n self.parser = parser\n\n def result(self):\n xs = list()\n ys = list()\n eys = list()\n exs = list()\n n_tokens = None\n with open(self.file_name) as f:\n for line in f:\n parsed = self.parser(line)\n\n LOGGER.debug('Parsed line\\n%s as %s', line, parsed)\n\n if not parsed:\n continue\n\n if n_tokens is None:\n n_tokens = len(parsed)\n\n if len(parsed) != n_tokens:\n raise Exception('Inconsistent number of fields '\n '(expected ' + str(n_tokens) + ') '\n 'returned when parsing' + self.file_name +\n '\\nThe problematic line was ' + line)\n\n if n_tokens == 2:\n x, y = parsed\n elif n_tokens == 3:\n x, y, ey = parsed\n eys.append(ey)\n elif n_tokens == 4:\n x, y, ey, ex = parsed\n eys.append(ey)\n exs.append(ex)\n\n xs.append(x)\n ys.append(y)\n\n if (len(xs) != len(ys) or\n (eys and len(ys) != len(eys)) or\n (exs and len(exs) != len(xs))):\n raise Exception('Inconsistent lengths of x/y/ey/ex arrays')\n\n LOGGER.debug('Parsing succeeded')\n LOGGER.debug('xs=%s', xs)\n LOGGER.debug('ys=%s', ys)\n LOGGER.debug('exs=%s', exs)\n LOGGER.debug('eys=%s', eys)\n\n xarr = np.array(xs)\n yarr = np.array(ys)\n eyarr = np.array(eys) if eys else None\n exarr = np.array(exs) if exs else None\n result = Result(edges=xarr, contents=yarr, errors=eyarr, xerrors=exarr)\n return result\n","repo_name":"arekfu/posthoc","sub_path":"posthoc/results/txt.py","file_name":"txt.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39983863579","text":"def addEle(lst,num):\n for i in range(0,len(lst)):\n lst[i].insert(0,num)\n return lst\n\ndef generator(lst):\n if(len(lst) == 0):\n return []\n if(len(lst) == 1):\n return[[lst[0]],[]]\n else:\n return generator(lst[1:]) + addEle(generator(lst[1:]),lst[0])\n\nt = int(input())\nfor i in range(0,t):\n n = int(input())\n numLst = list(map(int,input().split(' ')))\n subSet = list(filter(lambda lst:lst != [],generator(numLst)))\n for sb in subSet:\n if(sum(sb) == 0):\n print('Yes')\n break\n else:\n print('No')","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2545/60774/287328.py","file_name":"287328.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"27321358391","text":"try:\n from matplotlib.colors import LinearSegmentedColormap, ListedColormap\n from matplotlib import pyplot as plt\nexcept ImportError as e:\n print('Encountering ImportErrors due to issues with python package matplotlib',\n 'not playing nice with an OS X background',\n '\\nAttempting to fix...')\n plt = None\n LinearSegmentedColormap = None\n ListedColormap = None\n print('Fixed')\nimport numpy as np\n\n__all__ = ['wes_palettes',\n 'shiftedColorMap',\n 'create_colormap',\n 'discrete_colormap',\n 'rgb_to_hex',\n 'hex_to_rgb',\n ]\n\nwes_palettes = {\n 'BottleRocket1' : [\"#A42820\", \"#5F5647\", \"#9B110E\", \"#3F5151\", \"#4E2A1E\", \"#550307\", \"#0C1707\"],\n 'BottleRocket2' : [\"#FAD510\", \"#CB2314\", \"#273046\", \"#354823\", \"#1E1E1E\"],\n 'Rushmore1' : [\"#E1BD6D\", \"#EABE94\", \"#0B775E\", \"#35274A\" ,\"#F2300F\"],\n 'Rushmore' : [\"#E1BD6D\", \"#EABE94\", \"#0B775E\", \"#35274A\" ,\"#F2300F\"],\n 'Royal1' : [\"#899DA4\", \"#C93312\", \"#FAEFD1\", \"#DC863B\"],\n 'Royal2' : [\"#9A8822\", \"#F5CDB4\", \"#F8AFA8\", \"#FDDDA0\", \"#74A089\"],\n 'Zissou1' : [\"#3B9AB2\", \"#78B7C5\", \"#EBCC2A\", \"#E1AF00\", \"#F21A00\"],\n 'Darjeeling1' : [\"#FF0000\", \"#00A08A\", \"#F2AD00\", \"#F98400\", \"#5BBCD6\"],\n 'Darjeeling2' : [\"#ECCBAE\", \"#046C9A\", \"#D69C4E\", \"#ABDDDE\", \"#000000\"],\n 'Chevalier1' : [\"#446455\", \"#FDD262\", \"#D3DDDC\", \"#C7B19C\"],\n 'FantasticFox1' : [\"#DD8D29\", \"#E2D200\", \"#46ACC8\", \"#E58601\", \"#B40F20\"],\n 'Moonrise1' : [\"#F3DF6C\", \"#CEAB07\", \"#D5D5D3\", \"#24281A\"],\n 'Moonrise2' : [\"#798E87\", \"#C27D38\", \"#CCC591\", \"#29211F\"],\n 'Moonrise3' : [\"#85D4E3\", \"#F4B5BD\", \"#9C964A\", \"#CDC08C\", \"#FAD77B\"],\n 'Cavalcanti1' : [\"#D8B70A\", \"#02401B\", \"#A2A475\", \"#81A88D\", \"#972D15\"],\n 'GrandBudapest1' : [\"#F1BB7B\", \"#FD6467\", \"#5B1A18\", \"#D67236\"],\n 'GrandBudapest2' : [\"#E6A0C4\", \"#C6CDF7\", \"#D8A499\", \"#7294D4\"],\n 'IsleofDogs1' : [\"#9986A5\", \"#79402E\", \"#CCBA72\", \"#0F0D0E\", \"#D9D0D3\", \"#8D8680\"],\n 'IsleofDogs2' : [\"#EAD3BF\", \"#AA9486\", \"#B6854D\", \"#39312F\", \"#1C1718\"]}\n\ndef shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):\n '''\n Function to offset the \"center\" of a colormap. Useful for\n data with a negative min and positive max and you want the\n middle of the colormap's dynamic range to be at zero\n\n Input\n -----\n cmap : The matplotlib colormap to be altered\n start : Offset from lowest point in the colormap's range.\n Defaults to 0.0 (no lower ofset). Should be between\n 0.0 and `midpoint`.\n midpoint : The new center of the colormap. Defaults to\n 0.5 (no shift). Should be between 0.0 and 1.0. In\n general, this should be 1 - vmax/(vmax + abs(vmin))\n For example if your data range from -15.0 to +5.0 and\n you want the center of the colormap at 0.0, `midpoint`\n should be set to 1 - 5/(5 + 15)) or 0.75\n stop : Offset from highets point in the colormap's range.\n Defaults to 1.0 (no upper ofset). Should be between\n `midpoint` and 1.0.\n '''\n cdict = {\n 'red': [],\n 'green': [],\n 'blue': [],\n 'alpha': []\n }\n\n # regular index to compute the colors\n reg_index = np.linspace(start, stop, 257)\n\n # shifted index to match the data\n shift_index = np.hstack([\n np.linspace(0.0, midpoint, 128, endpoint=False),\n np.linspace(midpoint, 1.0, 129, endpoint=True)\n ])\n\n for ri, si in zip(reg_index, shift_index):\n r, g, b, a = cmap(ri)\n\n cdict['red'].append((si, r, r))\n cdict['green'].append((si, g, g))\n cdict['blue'].append((si, b, b))\n cdict['alpha'].append((si, a, a))\n\n newcmap = LinearSegmentedColormap(name, cdict)\n plt.register_cmap(cmap=newcmap)\n\n return newcmap\n\n\ndef create_colormap(colors=None, cmap_name=None, bins=10):\n \"\"\"Given a list of colors, creates a colormap with desired spacing\n\n Parameters\n ----------\n colors: list\n a list of colors to generate a colormap over\n cmap_name: str, by default None and 'my_list' is used\n Name of map to register\n bins: int, by default 10\n Number of steps to use in total map\n\n Returns\n -------\n\n \"\"\"\n if colors is None:\n # cmap_name = 'MoonriseKingdomCustom'\n # colors = ['#cb654f', '#d3b1a7', '#cfcb9c', '#8cbea3', '#dfba47',\n # '#fad77b', '#cdc08c','#9c964a', '#f4b5bd', '#86d4e4']\n colors = [\"#FF0000\", \"#00A08A\", \"#F2AD00\", \"#F98400\", \"#5BBCD6\",\n \"#E1BD6D\", \"#EABE94\", \"#0B775E\", \"#35274A\", \"#F2300F\"]\n if cmap_name is None:\n cmap_name = 'Rushmore1'\n if cmap_name is None:\n cmap_name = 'my_list'\n\n colormap = LinearSegmentedColormap.from_list(cmap_name, colors, N=bins)\n return colormap\n\ndef rgb_to_hex(rgb):\n \"\"\"Converts a rgb value to hex code\"\"\"\n return '#%02x%02x%02x' % rgb\n\ndef hex_to_rgb(value):\n \"\"\"converts a hexcode to rgb value\"\"\"\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))\n\n\ndef discrete_colormap(color_pool = None, N=8):\n \"\"\"create a color map with N (N<15) discrete colors and register it\"\"\"\n # define individual colors as hex values\n if color_pool is None:\n\n color_pool = [ '#bd2309', '#bbb12d', '#1480fa', '#14fa2f', '#000000',\n '#faf214', '#2edfea', '#ea2ec4', '#ea2e40', '#cdcdcd',\n '#577a4d', '#2e46c0', '#f59422', '#219774', '#8086d9' ]\n\n color_map = ListedColormap(color_pool[0:N], 'indexed')\n return color_map","repo_name":"LoganJF/Clumsy","sub_path":"Clumsy/misc/matplotlibmisc.py","file_name":"matplotlibmisc.py","file_ext":"py","file_size_in_byte":5588,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"10745987174","text":"import csv\nimport random\nimport numpy as np\n\nDRIVER_DATA_FILENAME = \"./datasets/data_driver_fix.csv\"\nCLIENT_DATA_FILENAME = \"./datasets/data_client_fix.csv\"\nBANNED_DATA_FILENAME = \"./datasets/banned_data.csv\"\n\nn = 20\nr_lat = np.arange(-7.365671, -7.226902, 0.000001)\nr_long = np.arange(112.652278, 112.790673, 0.000001)\nr_rating = 5\n\nheader = [\"id\", \"latitude\", \"longitude\", \"rating_driver\"]\nwith open(DRIVER_DATA_FILENAME, \"w\", newline=\"\") as f:\n print(\"Opening CSV\")\n writer = csv.writer(f)\n writer.writerow(header)\n\n print(\"Creating driver data\")\n for i in range(n):\n row = []\n row.append(i) # id\n row.append(r_lat[random.randint(0, len(r_lat))]) # lat\n row.append(r_long[random.randint(0, len(r_long))]) # long\n row.append(random.randint(0, r_rating)) # rating\n writer.writerow(row)\n print(\"Driver data created\")\nprint(\"Closing CSV\")\n\nheader = [\"id\", \"latitude\", \"longitude\", \"rating_client\"]\nwith open(CLIENT_DATA_FILENAME, \"w\", newline=\"\") as f:\n print(\"Opening CSV\")\n writer = csv.writer(f)\n writer.writerow(header)\n print(\"Creating driver data\")\n for i in range(n):\n row = []\n row.append(i) # id\n row.append(r_lat[random.randint(0, len(r_lat))]) # lat\n row.append(r_long[random.randint(0, len(r_long))]) # long\n row.append(random.randint(0, r_rating)) # rating\n writer.writerow(row)\n print(\"Client data created\")\nprint(\"Closing CSV\")\n\nheader = [\"client_id\", \"driver_id\"]\nwith open(BANNED_DATA_FILENAME, \"w\", newline=\"\") as f:\n print(\"Opening CSV\")\n writer = csv.writer(f)\n writer.writerow(header)\n print(\"Creating banned data\")\n for i in range(n):\n row = []\n row.append(random.randint(0, n-1)) # id client\n row.append(random.randint(0, n-1)) # id driver\n writer.writerow(row)\n print(\"Banned data created\")\nprint(\"Closing CSV\")","repo_name":"mtstnt/manpro","sub_path":"notebooks/data_gen.py","file_name":"data_gen.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"32249505643","text":"import json\nfrom time import sleep\nfrom tqdm import tqdm\nimport os\nimport openai\nfrom datetime import datetime\nfrom tool import *\nfrom typing import Dict, Any\nimport argparse\nfrom collections import Counter\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--key\", default='OPENAI_KEY', type=str)\nparser.add_argument(\"--start\", default=0, type=int)\nparser.add_argument(\"--greedy\", default=False, action='store_true')\nparser.add_argument(\"--dry_run\", default=False, action='store_true')\nparser.add_argument(\"--end\", default=-1, type=int)\nargs = parser.parse_args()\n\ndef create_reader_request_processed(example: Dict[str, Any]):\n prompt = 'Read the following text and table, and then write code to answer a question:\\n'\n if example['text']:\n prompt += example['text'] + '\\n'\n prompt += example['table'].strip() + '\\n'\n prompt += 'Question: {}\\n'.format(example['question'])\n prompt += '#Python\\n'\n return prompt\n\nprompt_4shot = \"\"\"Read the following text and table, and then write code to answer a question:\n( in millions ) | dec 282013 | dec 292012\navailable-for-sale investments | $ 18086 | $ 14001\ncash | 854 | 593\nequity method investments | 1038 | 992\nloans receivable | 1072 | 979\nnon-marketable cost method investments | 1270 | 1202\nreverse repurchase agreements | 800 | 2850\ntrading assets | 8441 | 5685\ntotal cash and investments | $ 31561 | $ 26302\nQuestion: what percentage of total cash and investments as of dec . 29 2012 was comprised of available-for-sale investments?\n#Python\navailable_for_sale_investments_dec_29_2012 = 14001\ntotal_cash_and_investments_dec_29_2012 = 26302\npercent_available_for_sale_investments_dec_29_2012 = available_for_sale_investments_dec_29_2012 / total_cash_and_investments_dec_29_2012\nans = percent_available_for_sale_investments_dec_29_2012\n\n\nRead the following text and table, and then write code to answer a question:\nthe chart shows that the firm posted market risk 2013related gains on 248 out of 261 days in this period , with 12 days exceeding $ 210 million .\ndecember 31 ( in millions ) | 1 basis point increase in jpmorgan chase 2019s credit spread\n2010 | $ 35\n2009 | $ 39\nQuestion: on what percent of trading days were there market gains above $ 210 million?\n#Python\ndays_with_market_gains_above_210_million = 12\ntotal_trading_days = 261\npercent_days_with_market_gains_above_210_million = days_with_market_gains_above_210_million / total_trading_days\nans = percent_days_with_market_gains_above_210_million\n\n\nRead the following text and table, and then write code to answer a question:\namerican tower corporation and subsidiaries notes to consolidated financial statements ( 3 ) consists of customer-related intangibles of approximately $ 75.0 million and network location intangibles of approximately $ 72.7 million . the customer-related intangibles and network location intangibles are being amortized on a straight-line basis over periods of up to 20 years .\n- | preliminary purchase price allocation\ncurrent assets | $ 8763\nnon-current assets | 2332\nproperty and equipment | 26711\nintangible assets ( 1 ) | 21079\nother non-current liabilities | -1349 ( 1349 )\nfair value of net assets acquired | $ 57536\ngoodwill ( 2 ) | 5998\nQuestion: for acquired customer-related and network location intangibles , what is the expected annual amortization expenses , in millions?\n#Python\ncustomer_related_intangibles = 75\nnetwork_location_intangibles = 72.7\nstraight_line_basis = 20\namortization_expenses = ( customer_related_intangibles + network_location_intangibles ) / straight_line_basis\nans = amortization_expenses\n\n\nRead the following text and table, and then write code to answer a question:\nthe aggregate commitment under the liquidity asset purchase agreements was approximately $ 23.59 billion and $ 28.37 billion at december 31 , 2008 and 2007 , respectively .\n( dollars in billions ) | 2008 amount | 2008 percent of total conduit assets | 2008 amount | percent of total conduit assets\nunited states | $ 11.09 | 46% ( 46 % ) | $ 12.14 | 42% ( 42 % )\naustralia | 4.30 | 17 | 6.10 | 21\ngreat britain | 1.97 | 8 | 2.93 | 10\nspain | 1.71 | 7 | 1.90 | 7\nitaly | 1.66 | 7 | 1.86 | 7\nportugal | 0.62 | 3 | 0.70 | 2\ngermany | 0.57 | 3 | 0.70 | 2\nnetherlands | 0.40 | 2 | 0.55 | 2\nbelgium | 0.29 | 1 | 0.31 | 1\ngreece | 0.27 | 1 | 0.31 | 1\nother | 1.01 | 5 | 1.26 | 5\ntotal conduit assets | $ 23.89 | 100% ( 100 % ) | $ 28.76 | 100% ( 100 % )\nQuestion: what is percentage change in total conduit asset from 2007 to 2008?\n#Python\ntotal_conduit_assets_2007 = 28.76\ntotal_conduit_assets_2008 = 23.89\nnet_change_in_total_conduit_assets = total_conduit_assets_2008 - total_conduit_assets_2007\npercent_change_in_total_conduit_assets = net_change_in_total_conduit_assets / total_conduit_assets_2007\nans = percent_change_in_total_conduit_assets\n\"\"\"\n\nif __name__ == \"__main__\":\n with open('data/finqa_test.json') as f:\n finqa_dev = json.load(f)\n\n now = datetime.now()\n dt_string = now.strftime(\"%m_%d_%H_%M\")\n\n correct, wrong = 0, 0\n\n if args.greedy:\n filename = f'outputs/finqa_new_s{args.start}_e{args.end}_{dt_string}.jsonl'\n else:\n filename = f'outputs/finqa_new_sc_s{args.start}_e{args.end}_{dt_string}.jsonl'\n writer = open(filename, 'w')\n\n for example in tqdm(finqa_dev):\n full_prompt = prompt_4shot + \"\\n\\n\"\n full_prompt += create_reader_request_processed(example)\n if args.dry_run:\n print(full_prompt)\n print('=======================')\n break\n\n if args.greedy:\n # greedy decoding\n got_result = False\n while not got_result:\n try:\n result = openai.Completion.create(\n engine='code-davinci-002',\n prompt=full_prompt,\n api_key=os.getenv(args.key),\n max_tokens=512,\n temperature=0.0,\n top_p=1,\n n=1,\n stop=['\\n\\n'],\n logprobs=1\n )\n got_result = True\n except Exception:\n sleep(3)\n else:\n # self-consistency decoding\n got_result = False\n while not got_result:\n try:\n result = openai.Completion.create(\n engine='code-davinci-002',\n prompt=full_prompt,\n api_key=os.getenv(args.key),\n max_tokens=512,\n temperature=0.5,\n top_p=1,\n n=30,\n stop=['\\n\\n'],\n logprobs=1\n )\n got_result = True\n except Exception as e:\n sleep(3)\n\n # self-consistency decoding or greedy decoding.\n result_counter = Counter()\n codes = parse_api_result(result)\n # handle the s&p500 case\n codes = [code.replace('&', '_') for code in codes]\n for r in codes:\n ans = safe_execute(r)\n ans = floatify_ans(ans)\n if ans is not None:\n result_counter.update([ans])\n\n if len(result_counter) > 0:\n prediction = result_counter.most_common(1)[0][0]\n else:\n prediction = None\n\n # Further Process according to FinQA dataset\n if prediction is not None:\n if type(prediction) == bool:\n if prediction:\n prediction = 'yes'\n else:\n prediction = 'no'\n elif type(prediction) == list:\n prediction = prediction[0]\n else:\n assert type(prediction) in [float, int], prediction\n\n if prediction is None:\n wrong += 1\n elif finqa_equal(prediction, example['answer'], False):\n correct += 1\n else:\n wrong += 1\n \n print('accuracy: ', correct / (correct + wrong))\n example.update({'generated': codes, 'executed': prediction})\n writer.write(json.dumps(example) + '\\n')\n\n print()\n print('accuracy: ', correct / (correct + wrong))\n writer.close()\n","repo_name":"wenhuchen/Program-of-Thoughts","sub_path":"run_finqa.py","file_name":"run_finqa.py","file_ext":"py","file_size_in_byte":8310,"program_lang":"python","lang":"en","doc_type":"code","stars":149,"dataset":"github-code","pt":"80"} +{"seq_id":"41237839447","text":"import numpy as np\r\n\r\ndef itr(acc_matrix, M, t):\r\n \"\"\"\r\n Information Transfer Rate (ITR) calculation.\r\n\r\n Input:\r\n - acc_matrix: Accuracy matrix\r\n - M: Number of characters\r\n - t: Total signal length (visual cue + desired signal length)\r\n\r\n Output:\r\n - ITR: Information Transfer Rate\r\n \"\"\"\r\n size_mat = np.shape(acc_matrix)\r\n itr_matrix = np.zeros(size_mat)\r\n for i in range(size_mat[0]):\r\n for j in range(size_mat[1]):\r\n p = acc_matrix[i, j]\r\n if p < 1/M:\r\n itr_matrix[i, j] = 0\r\n elif p == 1:\r\n itr_matrix[i, j] = np.log2(M) * (60/t)\r\n else:\r\n itr_matrix[i, j] = (np.log2(M) + p*np.log2(p) + (1-p)*np.log2((1-p)/(M-1))) * (60/t)\r\n return itr_matrix","repo_name":"taegyun12/DDNforSSVEP","sub_path":"itr.py","file_name":"itr.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"30324931592","text":"\"\"\"SA_ClientCenter URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.1/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\"\"\"\n\nfrom django.urls import path\nfrom UserInterfaceApp import views\n\nurlpatterns = [\n path('login_noAccount.html', views.login_noAccount_page),\n # path('login_Account.html', views.login_Account_page),\n path('inside.html', views.inside_page),\n path('logout', views.logout),\n path('Login_and_AddSession', views.Login_and_AddSession),\n path('alert_accessNO.html', views.alert_accessNO_page),\n path('GDPR.html', views.GDPR_page),\n path('alert_saved.html', views.alert_saved_page),\n path('alert_NOTuniquePhone.html', views.alert_NOTuniquePhone_page),\n]\n","repo_name":"hank1224/SA_ClientCenter","sub_path":"SA_ClientCenter/apps/UserInterfaceApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"73433490817","text":"from rest_framework import serializers\nfrom .models import ClienteModel, EspecieModel, MascotaModel, RazaModel\n\n\nclass MostrarRazaSerializer(serializers.ModelSerializer):\n class Meta:\n model = RazaModel\n fields = '__all__'\n\n\nclass EspecieSerializer(serializers.ModelSerializer):\n # este es el funcionamiento base del metodo save del serializer\n # def save(self):\n # especie = EspecieModel(especieNombre = self.validated_data.especieNombre)\n # especie.save()\n # self.instance = especie\n # return especie\n razas = MostrarRazaSerializer(\n source=\"especiesRaza\", many=True, read_only=True)\n\n def update(self):\n # el atributo instance es la instancia de la clase y me da acceso a todos los atributos de la clase\n print(self.instance)\n # es la data mandada por el front PERO que ya paso un filtro de validacion (que cumple con las condiciones definidas por el modelo) y se genera cuando se llama al metodo is_valid()\n print(self.validated_data)\n self.instance.especieNombre = self.validated_data.get(\"especieNombre\")\n self.instance.especieEstado = self.validated_data.get(\"especieEstado\")\n # el metodo save() es el metodo de los MODELOS que se encarga de hacer el guardado en la bd\n self.instance.save()\n # el atributo data es el encargo de maquillar la informacion para que el front la pueda visualizar sin problemas\n return self.data\n\n def delete(self):\n # Forma 1\n # self.instance.especieEstado = False\n # self.instance.save()\n # return self.instance\n # Forma 2\n if(self.instance):\n self.instance.especieEstado = False\n self.instance.save()\n return self.instance\n return None\n\n class Meta:\n # para que haga match con el model y pueda jalar las columnas con sus propiedades\n model = EspecieModel\n # indicar que columnas (atributos) quiero utilizar en este serializador\n # si queremos usar todos los campos => '__all__'\n # si queremos solamente usar ciertos campos (minoria) => ['campo1', 'campo2']\n fields = \"__all__\"\n # si queremos usar la mayora de campos y evitar una minoria => exclude = ['campos3', 'campo4']\n # NOTA: no se pueden usar los dos a la vez ya que genera ambiguedad\n # NOTA2: la unica forma de declara el exclude es mediante LIST, TUPLE ya que no admite el valor de __all__ si hacemos esto estariamos excluyendo todos los atributos del modelo\n # exclude = ('especieId',)\n\n\nclass EspecieVistaSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = EspecieModel\n exclude = ['especieEstado']\n\n\nclass RazaEscrituraSerializer(serializers.ModelSerializer):\n class Meta:\n model = RazaModel\n fields = '__all__'\n\n\nclass RazaVistaSerializer(serializers.ModelSerializer):\n especie = EspecieVistaSerializer()\n\n class Meta:\n model = RazaModel\n fields = '__all__'\n\n\nclass MascotaSerializer(serializers.ModelSerializer):\n class Meta:\n model = MascotaModel\n fields = '__all__'\n\n\nclass ClienteSerializer(serializers.ModelSerializer):\n class Meta:\n model = ClienteModel\n fields = '__all__'\n\n\nclass RegistroClienteSerializer(serializers.Serializer):\n # el valor del required x default es True\n # trim_whitespace lo que hace es remueve los espacios\n dni = serializers.CharField(max_length=9, required=True, min_length=8)\n email = serializers.EmailField(max_length=45, trim_whitespace=True)\n telefono = serializers.CharField(max_length=10, min_length=4)\n direccion = serializers.CharField(max_length=50)\n\n##########\n# Relacionado con el ejercicio\n####\n\n\nclass RazaSerializer(serializers.ModelSerializer):\n class Meta:\n model = RazaModel\n fields = '__all__'\n\n\nclass MascotaRazaSerializer(serializers.ModelSerializer):\n raza = RazaSerializer()\n\n class Meta:\n model = MascotaModel\n fields = '__all__'\n\n\nclass ClienteMascotaSerializer(serializers.ModelSerializer):\n mascotas = MascotaRazaSerializer(\n source=\"mascotasCliente\", many=True, read_only=True)\n\n class Meta:\n model = ClienteModel\n fields = '__all__'\n","repo_name":"ederivero/Virtual-Back-5","sub_path":"Semana 8/veterinaria/administracion/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"27285602814","text":"import os\nimport types\nfrom datetime import datetime\n\nimport actions\nimport boto_retry\nimport handlers\nimport handlers.task_tracking_table\nimport services\nfrom handlers.task_tracking_table import TaskTrackingTable\nfrom helpers import safe_dict, safe_json, full_stack\nfrom helpers.dynamodb import unpack_record\nfrom main import lambda_handler\nfrom outputs.queued_logger import QueuedLogger\nfrom outputs.result_notifications import ResultNotifications\n\nACTIVE_INSTANCES = \"InstanceCount\"\nCONCURRENCY_ID = handlers.TASK_TR_CONCURRENCY_ID\n\nENV_DEBUG_TASK_TACKING_HANDLER = \"DEBUG_TASK_TRACKING_HANDLER\"\n\nNEW_TASK = 0\nFINISHED_TASK = 1\nFINISHED_CONCURRENCY_TASK = 2\nCHECK_COMPLETION = 3\nDELETE_ITEM = 4\nSTART_WAITING_ACTION = 5\n\nTASK_ACTION_STRINGS = [\n \"New task\",\n \"Finished task\",\n \"Finished task with concurrency handling\",\n \"Check task completion\",\n \"Delete task item\",\n \"Start waiting task\"\n]\n\nWARN_DELETING_RESOURCES = \"Error deleting resources from bucket {} with key {}\"\n\nDEBUG_ACTION = \"Action is \\\"{}\\\" for task \\\"{}\\\", task-id is {}\"\nDEBUG_DRYRUN = \"Action will be executed in in dry-run mode\"\nDEBUG_LAMBDA = \"Lambda function invoked {}\"\nDEBUG_ACTION_PARAMETERS = \"Action parameters are {}\"\nDEBUG_RUNNING_ECS_TASK = \"Running {} step of task {} as ECS job\"\nDEBUG_RESULT = \"Handling actions tracking update took {:>.3f} seconds\"\nDEBUG_MEMORY_SIZE = \"Task memory allocation for executing lambda is {}\"\nDEBUG_LAMBDA_FUNCTION_ = \"Executing action with Lambda function {}, payload is {}\"\nDEBUG_START_WAITING = \"Waiting list count for ConcurrencyId \\\"{}\\\" is {}, action is \\\"{}\\\", starting waiting \" \\\n \"task \\\"{}\\\" with id {}\"\nDEBUG_WAITING = \"The waiting list for action \\\"{}\\\" with concurrency key \\\"{}\\\" is {}, the maximum number of concurrent \" \\\n \"running actions for this key is {}, action with id \\\"{}\\\" has been put in waiting state\"\n\nDEBUG_DELETING_RESOURCES_FROM_S3 = \"Deleting resource object {} from bucket {}, {}\"\nERR_RUNNING_TASK = \"Error running task {}, {}, {}\"\n\nLOG_STREAM = \"{}-{:0>4d}{:0>2d}{:0>2d}\"\nSCHEDULER_LAMBDA_FUNCTION_DEFAULT = \"SchedulerDefault\"\nSIZED_SCHEDULER_NAME_TEMPLATE = \"Scheduler{:0>04d}\"\n\n\nclass TaskTrackingHandler(object):\n \"\"\"\n Class to handle events triggered by inserting new items in the actions tracking table.\n \"\"\"\n\n def __init__(self, event, context):\n \"\"\"\n Initializes the instance.\n :param event: Handled event\n :param context: Context if running in Lambda\n \"\"\"\n self._context = context\n self._event = event\n self._tracking_table = None\n self._concurrency_table = None\n self.started_tasks = 0\n self.started_waiting_tasks = 0\n self.waiting_for_execution_tasks = 0\n self.started_completion_checks = 0\n self.finished_concurrency_tasks = 0\n self.done_work = False\n self.invoked_lambda_functions = []\n\n self.events_client = None\n self._s3_client = None\n self._db_client = None\n\n # setup logging\n classname = self.__class__.__name__\n dt = datetime.utcnow()\n logstream = LOG_STREAM.format(classname, dt.year, dt.month, dt.day)\n self._logger = QueuedLogger(logstream=logstream,\n context=self._context,\n buffersize=20,\n debug=os.getenv(ENV_DEBUG_TASK_TACKING_HANDLER, \"false\").lower() == \"true\")\n\n @classmethod\n def is_handling_request(cls, event, context):\n\n # In simulation the handler is called directly when inserting or updating items in the table\n if handlers.running_local(context):\n return False\n\n if event.get(\"Records\", [{}])[0].get(\"eventSource\", \"\") != \"aws:dynamodb\":\n return False\n\n source_arn = event[\"Records\"][0][\"eventSourceARN\"]\n table_name = source_arn.split(\"/\")[1]\n return table_name in [os.getenv(handlers.ENV_ACTION_TRACKING_TABLE), os.getenv(handlers.ENV_CONCURRENCY_TABLE)]\n\n @classmethod\n def task_string(cls, action):\n return TASK_ACTION_STRINGS[action] if 0 <= action < len(TASK_ACTION_STRINGS) else \"Unknown\"\n\n @property\n def tracking_table(self):\n \"\"\"\n Gets an instance of the tracking table and use it in subsequent calls\n :return: Instance tracking table\n \"\"\"\n if self._tracking_table is None:\n self._tracking_table = TaskTrackingTable(self._context, self._logger)\n return self._tracking_table\n\n @property\n def s3_client(self):\n\n if self._s3_client is None:\n self._s3_client = boto_retry.get_client_with_retries(\"s3\", [\"delete_item\"], logger=self._logger)\n return self._s3_client\n\n @property\n def db_client(self):\n\n if self._db_client is None:\n self._db_client = boto_retry.get_client_with_retries(\"dynamodb\", [\"delete_item\"], logger=self._logger)\n return self._db_client\n\n def _get_action_concurrency_key(self, item):\n \"\"\"\n Gets the concurrency key for a tasks action\n :param item: The task item\n :return: The concurrency key for the tasks action\n \"\"\"\n action = item[handlers.TASK_TR_ACTION]\n # get the name of the optional method to return the concurrency key\n action_class = actions.get_action_class(action)\n concurrency_key_method = getattr(action_class, handlers.ACTION_CONCURRENCY_KEY_METHOD, None)\n\n # prepare parameters for calling static function that returns the concurrency key\n if concurrency_key_method is not None:\n get_key_params = {\n actions.ACTION_PARAM_RESOURCES: handlers.get_item_resource_data(item, self._context),\n actions.ACTION_PARAM_ACCOUNT: item[handlers.TASK_TR_ACCOUNT],\n actions.ACTION_PARAM_STACK: os.getenv(handlers.ENV_STACK_NAME),\n actions.ACTION_PARAM_STACK_ID: os.getenv(handlers.ENV_STACK_ID),\n actions.ACTION_PARAM_TASK_ID: item[handlers.TASK_TR_ID],\n actions.ACTION_PARAM_TASK: item[handlers.TASK_TR_NAME]\n }\n get_key_params.update(item.get(handlers.TASK_TR_PARAMETERS))\n return concurrency_key_method(get_key_params)\n else:\n # if this method is not available for action then use the name of the action as the key\n return action\n\n def _enter_waiting_list(self, concurrency_key):\n \"\"\"\n Adds 1 to waiting list counter for the specified concurrency key and returns new value\n :param concurrency_key: Concurrency key for counter\n :return: Updated counter\n \"\"\"\n\n # update/read counter for the concurrency key\n if not handlers.running_local(self._context):\n resp = self.concurrency_table.update_item_with_retries(Key={CONCURRENCY_ID: concurrency_key},\n UpdateExpression=\"ADD InstanceCount :one SET RunNext=:run\",\n ExpressionAttributeValues={\":one\": 1, \":run\": False},\n ReturnValues=\"UPDATED_NEW\")\n return int(resp[\"Attributes\"].get(\"InstanceCount\", 0))\n else:\n resp = self.concurrency_table.get_item_with_retries(Key={CONCURRENCY_ID: concurrency_key})\n return resp.get(\"Item\", {}).get(ACTIVE_INSTANCES, 0)\n\n def _leave_waiting_list(self, task_id, concurrency_key):\n \"\"\"\n Subtracts 1 from waiting list counter for the specified concurrency key and returns new value. If the counter reaches 0\n then the entry for the concurrency key is removed\n :param concurrency_key: Concurrency key for counter\n :return: Updated counter\n \"\"\"\n\n # make a consistent read of the task\n self.tracking_table.get_task_item(task_id)\n\n if not handlers.running_local(self._context):\n\n resp = self.concurrency_table.update_item_with_retries(Key={CONCURRENCY_ID: concurrency_key},\n UpdateExpression=\"ADD InstanceCount :min_one SET RunNext=:run\",\n ExpressionAttributeValues={\":min_one\": -1, \":run\": True},\n ReturnValues=\"UPDATED_NEW\")\n count = max(0, int(resp[\"Attributes\"].get(ACTIVE_INSTANCES, 0)))\n\n # remove entry if no more waiting items for this key\n if count == 0:\n self.concurrency_table.delete_item_with_retries(Key={CONCURRENCY_ID: concurrency_key})\n else:\n resp = self.concurrency_table.get_item_with_retries(Key={CONCURRENCY_ID: concurrency_key})\n count = resp.get(\"Item\", {}).get(ACTIVE_INSTANCES, 0)\n TaskTrackingTable._run_local_stream_event(os.getenv(handlers.ENV_CONCURRENCY_TABLE), \"UPDATE\",\n {\"ConcurrencyId\": concurrency_key, \"InstanceCount\": count},\n {\"ConcurrencyId\": concurrency_key, \"InstanceCount\": count + 1},\n self._context)\n\n return count\n\n @property\n def concurrency_table(self):\n \"\"\"\n Returns table to store last execution time for this handler.\n :return: table to store last execution time for this handler\n \"\"\"\n if self._concurrency_table is None:\n tablename = os.getenv(handlers.ENV_CONCURRENCY_TABLE)\n\n self._logger.debug(\"Using concurrency table {}\", tablename)\n\n self._concurrency_table = services.get_session().resource(\"dynamodb\").Table(tablename)\n boto_retry.add_retry_methods_to_resource(self._concurrency_table, [\"update_item\", \"get_item\", \"delete_item\"],\n context=self._context)\n\n return self._concurrency_table\n\n def _is_wait_listed(self, item):\n \"\"\"\n Test if there is a max concurrency level for the tasks action. If this is the case then a concurrency key is retrieved\n from the action and it is used to update the counter in the concurrency table for that key. The updated counter is tested\n against the max concurrency level for the tasks action\n :param item: task item\n :return: True if counter for tasks action concurrency key > mac concurrency level, False if it is less or equal or the\n action has no max concurrency level\n \"\"\"\n\n action = item.get(handlers.TASK_TR_ACTION, None)\n if action is None:\n return False\n\n action_properties = actions.get_action_properties(action)\n\n # test if there are concurrency restrictions\n max_action_concurrency = action_properties.get(actions.ACTION_MAX_CONCURRENCY)\n\n # no maximum\n if max_action_concurrency in [None, 0]:\n return False\n\n # property may be a lambda function, call the function with parameters of task as lambda parameters\n if types.FunctionType == type(max_action_concurrency):\n parameters = item[handlers.TASK_TR_PARAMETERS]\n max_action_concurrency = max_action_concurrency(parameters)\n if max_action_concurrency in [None, 0]:\n return False\n\n # get the key for the tasks action\n concurrency_key = self._get_action_concurrency_key(item)\n # enter the waiting list for that key\n count = int(self._enter_waiting_list(concurrency_key))\n\n # set status to waiting if count > max concurrency level\n status = handlers.STATUS_WAITING if count >= int(max_action_concurrency) else None\n\n # store the concurrency key twice, the concurrency id is used for the index in the GSI and is removed after the\n # action is handled so it does not longer show in the GSI, but we keep another copy in the task tracking table that\n # we need to decrement the counter in the waiting list and possible start waiting instances with the same key\n self.tracking_table.update_task(item[handlers.TASK_TR_ID],\n task=item[handlers.TASK_TR_NAME],\n task_metrics=item.get(handlers.TASK_TR_METRICS, False),\n status=status,\n status_data={\n handlers.TASK_TR_CONCURRENCY_KEY: concurrency_key,\n handlers.TASK_TR_CONCURRENCY_ID: concurrency_key\n })\n\n if count > max_action_concurrency:\n self._logger.debug(DEBUG_WAITING, item[handlers.TASK_TR_ACTION], concurrency_key, count,\n max_action_concurrency, item[handlers.TASK_TR_ID])\n return True\n\n return False\n\n def _start_task_execution(self, task_item, action=handlers.HANDLER_ACTION_EXECUTE):\n \"\"\"\n Creates an instance of the lambda function that executes the tasks action. It first checks is the action has specific memory\n requirements and based on this it creates a copy of this instance or one configured for the required memory. All\n information for executing the action is passed in the event.\n :param task_item: Task item for which action is executed\n :return:\n \"\"\"\n\n try:\n\n self._logger.debug(\"Entering start_task_execution ({}) with task {}\", action, safe_json(task_item, indent=3))\n\n # Create event for execution of the action and set its action so that is picked up by the execution handler\n event = {i: task_item.get(i) for i in task_item}\n event[handlers.HANDLER_EVENT_ACTION] = action\n\n self._logger.debug(DEBUG_ACTION, task_item[handlers.TASK_TR_ACTION],\n task_item[handlers.TASK_TR_NAME],\n task_item[handlers.TASK_TR_ID])\n\n self._logger.debug(DEBUG_ACTION_PARAMETERS,\n safe_json(task_item.get(handlers.TASK_TR_PARAMETERS, {}), indent=3))\n\n # get memory allocation for executing the task\n lambda_size = handlers.TASK_TR_COMPLETION_SIZE \\\n if action == handlers.HANDLER_ACTION_TEST_COMPLETION \\\n else handlers.TASK_TR_EXECUTE_SIZE\n\n execute_lambda_size = task_item.get(lambda_size, actions.ACTION_SIZE_STANDARD)\n\n if execute_lambda_size == actions.ACTION_USE_ECS:\n ecs_memory = task_item.get(handlers.TASK_EXECUTE_ECS_MEMORY\n if action == handlers.HANDLER_ACTION_EXECUTE\n else handlers.TASK_COMPLETION_ECS_MEMORY, None)\n else:\n ecs_memory = None\n\n if not handlers.running_local(self._context):\n\n self._logger.debug(DEBUG_MEMORY_SIZE, execute_lambda_size)\n\n if execute_lambda_size != actions.ACTION_USE_ECS:\n\n # create event payload\n payload = str.encode(safe_json(event))\n\n # determine which lambda to execute on\n function_name = \"{}-{}-{}\".format(os.getenv(handlers.ENV_STACK_NAME),\n os.getenv(handlers.ENV_LAMBDA_NAME),\n execute_lambda_size)\n\n self._logger.debug(\"Running execution of task on lambda function {}\", function_name)\n\n self._logger.debug(DEBUG_LAMBDA_FUNCTION_, function_name, payload)\n # start lambda function\n lambda_client = boto_retry.get_client_with_retries(\"lambda\", [\"invoke\"], context=self._context,\n logger=self._logger)\n resp = lambda_client.invoke_with_retries(FunctionName=function_name,\n InvocationType=\"Event\",\n LogType=\"None\",\n Payload=payload)\n\n task_info = {\n \"id\": task_item[handlers.TASK_TR_ID],\n \"task\": task_item[handlers.TASK_TR_NAME],\n \"action\": task_item[handlers.TASK_TR_ACTION],\n \"payload\": payload,\n \"status-code\": resp[\"StatusCode\"]\n }\n\n self._logger.debug(DEBUG_LAMBDA, safe_json(task_info, indent=2))\n self.invoked_lambda_functions.append(task_info)\n else:\n # run as ECS job\n ecs_args = {\n \"subnets\": os.getenv('AWSVPC_SUBNETS'),\n \"securitygroups\": os.getenv('AWSVPC_SECURITYGROUPS'),\n \"assignpublicip\": os.getenv('AWSVPC_ASSIGNPUBLICIP'),\n handlers.HANDLER_EVENT_ACTION: action,\n handlers.TASK_NAME: task_item[handlers.TASK_TR_NAME],\n handlers.TASK_TR_ID: task_item[handlers.TASK_TR_ID]}\n\n self._logger.debug(DEBUG_RUNNING_ECS_TASK, action, task_item[handlers.TASK_TR_NAME])\n handlers.run_as_ecs_job(ecs_args, ecs_memory_size=ecs_memory, context=self._context, logger=self._logger)\n\n else:\n lambda_handler(event, self._context)\n\n ResultNotifications(context=self._context, logger=self._logger).publish_started(task_item)\n\n except Exception as ex:\n self._logger.error(ERR_RUNNING_TASK, task_item, str(ex), full_stack())\n\n def _handle_new_task_item(self, task_item):\n \"\"\"\n Handles stream updates for new tasks added to the task tracking table\n :param task_item:\n :return:\n \"\"\"\n self._logger.debug(\"Handling new task logic\")\n # tasks can be wait listed if there is a max concurrency level for its action\n if self._is_wait_listed(task_item):\n self.waiting_for_execution_tasks += 1\n return\n\n # if not wait listed start the action for the task\n self.started_tasks += 1\n self._start_task_execution(task_item)\n\n def _handle_completed_concurrency_item(self, task_item):\n\n self._logger.debug(\"Handling completed concurrency logic\")\n # gets the concurrency key for the task\n concurrency_key = task_item[handlers.TASK_TR_CONCURRENCY_KEY]\n self._logger.debug(\"Handling completed task with ConcurrencyKey {}\", concurrency_key)\n\n # use the concurrency key to decrement the counter for that key in the waiting list\n count = self._leave_waiting_list(task_item[handlers.TASK_TR_ID], concurrency_key)\n self._logger.debug(\"Concurrency count for ConcurrencyKey {} is {}\", concurrency_key, count)\n\n self.finished_concurrency_tasks += 1\n\n ResultNotifications(context=self._context, logger=self._logger).publish_ended(task_item)\n\n def _handle_finished_task_without_completion(self, task_item):\n ResultNotifications(context=self._context, logger=self._logger).publish_ended(task_item)\n\n def _handle_start_waiting_action(self, concurrency_item):\n\n self._logger.debug(\"Handling start waiting task logic\")\n # gets the concurrency key for the task\n concurrency_id = concurrency_item[handlers.TASK_TR_CONCURRENCY_ID]\n self._logger.debug(\"Handling completed task with ConcurrencyId {}\", concurrency_id)\n\n waiting_list = self.tracking_table.get_waiting_tasks(concurrency_id)\n\n self._logger.debug(\" List of waiting tasks for ConcurrencyKey {} is {}\", concurrency_id, safe_json(waiting_list, indent=3))\n if len(waiting_list) > 0:\n count = concurrency_item.get(ACTIVE_INSTANCES, 0)\n oldest_waiting_task = sorted(waiting_list, key=lambda w: w[handlers.TASK_TR_CREATED_TS])[0]\n self._logger.debug(DEBUG_START_WAITING, concurrency_id, count,\n oldest_waiting_task[handlers.TASK_TR_ACTION],\n oldest_waiting_task[handlers.TASK_TR_NAME],\n oldest_waiting_task[handlers.TASK_TR_ID])\n self.started_waiting_tasks += 1\n self._start_task_execution(oldest_waiting_task)\n\n def _handle_check_completion(self, task_item):\n self._logger.debug(\"Handling test for completion logic\")\n if task_item.get(handlers.TASK_TR_RUN_LOCAL, False) and not handlers.running_local(self._context):\n self._logger.debug(\"Item running in local mode skipped\")\n return\n\n self.started_completion_checks += 1\n self._start_task_execution(task_item=task_item, action=handlers.HANDLER_ACTION_TEST_COMPLETION)\n\n def _handle_deleted_item(self, task_item):\n\n if task_item.get(handlers.TASK_TR_S3_RESOURCES, False):\n\n bucket = os.getenv(handlers.ENV_RESOURCE_BUCKET)\n key = task_item[handlers.TASK_TR_ID] + \".json\"\n try:\n self._logger.debug(DEBUG_DELETING_RESOURCES_FROM_S3, bucket, key)\n self.s3_client.delete_object_with_retries(Bucket=bucket, Key=key)\n except Exception as ex:\n self._logger.warning(WARN_DELETING_RESOURCES, bucket, key, ex)\n\n def handle_request(self):\n \"\"\"\n Handles the event triggered by updates to the actions tracking table.\n :return: results of handling selected updates\n \"\"\"\n\n def tasks_items_to_execute():\n \"\"\"\n Generator function that selects all record items from the event that need processing.\n :return:\n \"\"\"\n\n def table_name(rec):\n source_arn = rec[\"eventSourceARN\"]\n return source_arn.split(\"/\")[1]\n\n def from_tracking_table(rec):\n return table_name(rec) == os.getenv(handlers.ENV_ACTION_TRACKING_TABLE)\n\n def from_concurrency_table(rec):\n return table_name(rec) == os.getenv(handlers.ENV_CONCURRENCY_TABLE)\n\n def get_old_image(task_record):\n return task_record[\"dynamodb\"].get(\"OldImage\", {})\n\n def get_new_image(task_record):\n return task_record[\"dynamodb\"].get(\"NewImage\", {})\n\n def get_new_status(task_record):\n return get_new_image(task_record).get(handlers.TASK_TR_STATUS, {}).get(\"S\")\n\n def get_old_status(task_record):\n return get_new_image(task_record).get(handlers.TASK_TR_STATUS, {}).get(\"S\")\n\n def is_task_tracking_table_update(task_record):\n if not from_tracking_table(task_record):\n return False\n return task_record[\"eventName\"] in [\"UPDATE\", \"MODIFY\"]\n\n def is_task_done(task_record):\n\n if not is_task_tracking_table_update(task_record):\n return False\n\n new_status = get_new_status(task_record)\n old_status = get_old_status(task_record)\n\n if old_status != new_status:\n return False\n return new_status in handlers.task_tracking_table.NOT_LONGER_ACTIVE_STATUSES\n\n def is_task_with_concurrency(task_record):\n return get_new_image(task_record).get(handlers.TASK_TR_CONCURRENCY_KEY, {}).get(\"S\") is not None\n\n def get_old_last_update(task_record):\n return get_old_image(task_record).get(handlers.TASK_TR_LAST_WAIT_COMPLETION, {}).get(\"S\")\n\n def get_new_last_update(task_record):\n return get_new_image(task_record).get(handlers.TASK_TR_LAST_WAIT_COMPLETION, {}).get(\"S\")\n\n def is_delete_task(task_record):\n return from_tracking_table(r) and task_record[\"eventName\"] == \"REMOVE\"\n\n def is_new_task(task_record):\n if from_tracking_table(r) and task_record[\"eventName\"] == \"INSERT\":\n return get_new_status(task_record) == handlers.STATUS_PENDING\n return False\n\n def is_completed_with_concurrency(task_record):\n return is_task_done(task_record) and is_task_with_concurrency(task_record)\n\n def is_completed_without_concurrency(task_record):\n\n return is_task_done(task_record) and not is_task_with_concurrency(task_record)\n\n def is_wait_for_completion(task_record):\n\n if not is_task_tracking_table_update(task_record):\n return False\n\n if get_old_status(task_record) != handlers.STATUS_WAIT_FOR_COMPLETION or \\\n get_new_status(task_record) != handlers.STATUS_WAIT_FOR_COMPLETION:\n return False\n\n return get_old_last_update(task_record) != get_new_last_update(task_record)\n\n def is_concurrency_task_completed(concurrency_record):\n if not from_concurrency_table(concurrency_record):\n return False\n\n if concurrency_record[\"eventName\"] == \"REMOVE\":\n return False\n\n return concurrency_record[\"dynamodb\"].get(\"NewImage\", {}).get(\"RunNext\", {}).get(\"BOOL\", False)\n\n def get_action_type(rec):\n\n if is_new_task(rec):\n return NEW_TASK\n\n if is_completed_without_concurrency(rec):\n return FINISHED_TASK\n\n if is_completed_with_concurrency(rec):\n return FINISHED_CONCURRENCY_TASK\n\n if is_wait_for_completion(rec):\n return CHECK_COMPLETION\n\n if is_delete_task(rec):\n return DELETE_ITEM\n\n if is_concurrency_task_completed(rec):\n return START_WAITING_ACTION\n\n return None\n\n for r in self._event.get(\"Records\"):\n\n self._logger.debug(\"Record to process is {}\", safe_json(r, indent=2))\n\n if r.get(\"eventSource\") == \"aws:dynamodb\":\n\n image_used = \"NewImage\" if \"NewImage\" in r[\"dynamodb\"] else \"OldImage\"\n\n if r[\"dynamodb\"].get(\"NewImage\", {}).get(handlers.TASK_TR_ACTION) is None and \\\n r[\"dynamodb\"].get(\"OldImage\", {}).get(handlers.TASK_TR_ACTION) is not None:\n continue\n\n self._logger.debug_enabled = r[\"dynamodb\"][image_used].get(handlers.TASK_TR_DEBUG, {}).get(\"BOOL\", False)\n\n update_to_handle = get_action_type(r)\n\n if update_to_handle is not None:\n yield update_to_handle, r\n else:\n self._logger.debug(\"No action for record\")\n\n try:\n\n start = datetime.now()\n\n task_handlers = [\n self._handle_new_task_item,\n self._handle_finished_task_without_completion,\n self._handle_completed_concurrency_item,\n self._handle_check_completion,\n self._handle_deleted_item,\n self._handle_start_waiting_action\n ]\n\n for task_tracking_update_type, record in tasks_items_to_execute():\n self.done_work = True\n\n used_image = \"OldImage\" if record[\"eventName\"] == \"REMOVE\" else \"NewImage\"\n image = record[\"dynamodb\"][used_image]\n handled_item = unpack_record(image)\n self._logger.debug_enabled = handled_item.get(handlers.TASK_TR_DEBUG, False)\n\n self._logger.debug(\"Executing handler function {} for type {} ({})\",\n task_handlers[task_tracking_update_type].__name__, self.task_string(task_tracking_update_type),\n task_tracking_update_type)\n task_handlers[task_tracking_update_type](handled_item)\n\n if not self.done_work:\n self._logger.clear()\n\n running_time = float((datetime.now() - start).total_seconds())\n if self.done_work:\n self._logger.debug(DEBUG_RESULT, running_time)\n\n return safe_dict({\n \"datetime\": datetime.now().isoformat(),\n \"waiting-for-execution\": self.waiting_for_execution_tasks,\n \"started-check-for-completion\": self.started_completion_checks,\n \"started-execution\": self.started_tasks,\n \"started-waiting\": self.started_waiting_tasks,\n \"completed-concurrency-tasks\": self.finished_concurrency_tasks,\n \"running-time\": running_time\n })\n\n finally:\n self._logger.flush()\n","repo_name":"aws-solutions/aws-ops-automator","sub_path":"source/code/handlers/task_tracking_handler.py","file_name":"task_tracking_handler.py","file_ext":"py","file_size_in_byte":29085,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"80"} +{"seq_id":"18937158231","text":"#importacion de documentos y librerias\n\nimport io\nimport funciones as fn\n\n#Menu \nmenu = ''' ----------------------------------------\nBienvenidos a la agenda de beneficiarios (Universidad el Bosque)\n----------------------------------------\n\nPor favor eliga una opcion valida.\n\n 1 - Ingrese nuevo ususario.\n 2 - Buscar usuario.\n 3 - Borrar usuario.\n 4 - Adicionar usuario. \n 5 - Lista de usuarios registrados.\n 6 - Buscar por letra en nombre del beneficiario.\n 7 - Salir.\n\n----------------------------------------\n¿ Cual es su opción?: '''\n\n#Lectura del archivo Agenda.txt, para su llenado.\ndatos=open('Agenda.txt' , 'r')\nflag=True \nlineas=datos.readlines()\n\ndatos.close()\n\n#Ingreso de datos\n\n#Ingreso de datos al menu \n\nescoger = int(input(menu))\nif escoger == 1:\n datos=open('Agenda.txt' , 'r+')\n datos.close()\n cantidad= int(input(\"Digite No. de usuarios que desea ingresar: \"))\n for i in range (cantidad):\n L=[]\n print('\\nBeneficiario N°', i+1)\n nombre=input(\"Digite nombre completo: \").lower().title()\n L.append(nombre)\n documento=input(\"Digite el número de documento: \")\n L.append(documento)\n celular=input(\"Digite el número de celular: \")\n L.append(celular)\n print(\"________________________________________\")\n print(\"El nombre del usuario registrado es : \",nombre)\n print(\"El nel numero de documentacion del usuario es : \",documento)\n print(\"El numero del usuario es : \",celular)\n print(\"________________________________________\")\n\n datos=open('Agenda.txt' , 'a')\n for variable in L:\n datos.write(variable)\n datos.write(\"\\n\")\n datos.close() \n\n#Funciones Menu.\nwhile True:\n escoger = int(input(menu))\n if escoger==2: \n busqueda=fn.buscar(lineas)\n \n elif escoger==3:\n borrado=fn.borrar(lineas)\n\n elif escoger==4:\n adicion=fn.adicionar(lineas)\n \n elif escoger==5:\n lista=fn.listar(lineas)\n\n elif escoger==6:\n inicial=fn.buscar_letra()\n\n elif escoger==7:\n break","repo_name":"borismg04/Python-Fundamentos","sub_path":"CRUD (Agenda)/Reto_No_6_7.py","file_name":"Reto_No_6_7.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"14402143811","text":"from tkinter import *\r\nimport tkinter.messagebox as tkMessageBox\r\nfrom PIL import Image, ImageTk,ImageDraw ,ImageFont\r\nimport socket, threading, sys, traceback, os\r\nfrom time import time\r\nfrom RtpPacket import RtpPacket\r\nimport sys\r\n\r\nCACHE_FILE_NAME = \"cache-\"\r\nCACHE_FILE_EXT = \".jpg\"\r\na=0\r\nclass Client:\r\n\tINIT = 0\r\n\tREADY = 1\r\n\tPLAYING = 2\r\n\tstate = INIT\r\n\t\r\n\tSETUP = 0\r\n\tPLAY = 1\r\n\tPAUSE = 2\r\n\tTEARDOWN = 3\r\n\tREPLAY=4\r\n\tDESCRIBE=5\r\n\tSPEED=6\r\n\r\n\tspeed_arr=['Speed: x1','Speed: x1.25','Speed: x1.5','Speed: x2','Speed: x4','Speed: x0.5','Speed: x0.75']\r\n\tspeed_idx=0\r\n\t# Initiation..\r\n\tdef __init__(self, master, serveraddr, serverport, rtpport, filename):\r\n\t\tself.master = master\r\n\t\tself.master.protocol(\"WM_DELETE_WINDOW\", self.handler)\r\n\t\tself.createWidgets()\r\n\t\tself.serverAddr = serveraddr\r\n\t\tself.serverPort = serverport\r\n\t\tself.rtpPort = rtpport\r\n\t\tself.fileName = filename\r\n\t\tself.rtspSeq = 0\r\n\t\tself.sessionId = 0\r\n\t\tself.requestSent = -1\r\n\t\tself.teardownAcked = 0\r\n\t\tself.connectToServer()\r\n\t\tself.frameNbr = 0\r\n\t\tself.current_fps=0\r\n\t\tself.prev_fps=None #for counting the fps\r\n\r\n\t\tself.video_current_data_rate=0\r\n\t\tself.prev_datarate=None \r\n\tdef createWidgets(self):\r\n\t\t\"\"\"Build GUI.\"\"\"\r\n\t\t# Create Setup button #lẽ ra là setup\r\n\t\tself.setup = Button(self.master, width=16, padx=3, pady=3)\r\n\t\tself.setup[\"text\"] = \"Play\"\r\n\t\tself.setup[\"command\"] = self.setupMovie\r\n\t\tself.setup.grid(row=1, column=0, padx=2, pady=2)\r\n\t\t\r\n\t\t# # Create Play button\t\t\r\n\t\t# self.start = Button(self.master, width=16, padx=3, pady=3)\r\n\t\t# self.start[\"text\"] = \"Play\"\r\n\t\t# self.start[\"command\"] = self.playMovie\r\n\t\t# self.start.grid(row=1, column=1, padx=2, pady=2)\r\n\t\t\r\n\t\t# Create Pause button\t\t\t\r\n\t\tself.pause = Button(self.master, width=16, padx=3, pady=3)\r\n\t\tself.pause[\"text\"] = \"Pause\"\r\n\t\tself.pause[\"command\"] = self.pauseMovie\r\n\t\tself.pause.grid(row=1, column=1, padx=2, pady=2)\r\n\t\t\r\n\t\t# Create Describe button\t\t\t\r\n\t\tself.pause = Button(self.master, width=20, padx=3, pady=3)\r\n\t\tself.pause[\"text\"] = \"Describe\"\r\n\t\tself.pause[\"command\"] = self.describeMovie\r\n\t\tself.pause.grid(row=1, column=2, padx=2, pady=2)\r\n\r\n\t\t# Create Teardown button\r\n\t\tself.teardown = Button(self.master, width=16, padx=3, pady=3)\r\n\t\tself.teardown[\"text\"] = \"Teardown\"\r\n\t\tself.teardown[\"command\"] = self.exitClient\r\n\t\tself.teardown.grid(row=1, column=3, padx=2, pady=2)\r\n\t\t\r\n\t\t# Create Replay button\r\n\t\tself.teardown = Button(self.master, width=16, padx=3, pady=3)\r\n\t\tself.teardown[\"text\"] = \"Replay\"\r\n\t\tself.teardown[\"command\"] = self.replayMovie\r\n\t\tself.teardown.grid(row=1, column=4, padx=2, pady=2)\r\n\r\n\t\t# Create Speed button\r\n\t\tself.speed = Button(self.master, width=16, padx=3, pady=3)\r\n\t\tself.speed[\"text\"] = self.speed_arr[self.speed_idx]\r\n\t\tself.speed[\"command\"] = self.speedMovie\r\n\t\tself.speed.grid(row=2, column=0, padx=2, pady=2)\r\n\r\n\t\t# Create a label to display the movie\r\n\t\tself.label = Label(self.master, height=19)\r\n\t\tself.label.grid(row=0, column=0, columnspan=5, sticky=W+E+N+S, padx=5, pady=5) \r\n\t\r\n\tdef setupMovie(self):\r\n\t\t\"\"\"Setup button handler.\"\"\"\r\n\t\tif self.state == self.INIT:\r\n\t\t\tself.sendRtspRequest(self.SETUP)\r\n\t\telse:\r\n \t\t\tself.playMovie()\r\n\t\r\n\tdef exitClient(self):\r\n\t\t\"\"\"Teardown button handler.\"\"\"\r\n\t\tself.sendRtspRequest(self.TEARDOWN)\t\t\r\n\t\tself.master.destroy() # Close the gui window\r\n\t\tos.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video\r\n\r\n\t\r\n\tdef pauseMovie(self):\r\n\t\t\"\"\"Pause button handler.\"\"\"\r\n\t\tif self.state == self.PLAYING:\r\n\t\t\tself.sendRtspRequest(self.PAUSE)\r\n\t\r\n\tdef playMovie(self):\r\n\t\t\"\"\"Play button handler.\"\"\"\r\n\t\tif self.state == self.READY:\r\n\t\t\t# Create a new thread to listen for RTP packets\r\n\t\t\tthreading.Thread(target=self.listenRtp).start()\r\n\t\t\tself.playEvent = threading.Event()\r\n\t\t\tself.playEvent.clear()\r\n\t\t\tself.sendRtspRequest(self.PLAY)\r\n\t\r\n\tdef describeMovie(self):\r\n \t\tself.sendRtspRequest(self.DESCRIBE)\r\n\r\n\tdef replayMovie(self):\r\n\t\tself.teardownAcked = 0\r\n\t\tself.frameNbr = 0\r\n\t\tself.sendRtspRequest(self.REPLAY)\r\n\r\n\tdef speedMovie(self):\r\n\t\tself.sendRtspRequest(self.SPEED)\r\n\t\tpass\r\n\tdef listenRtp(self):\t\t\r\n\t\t\"\"\"Listen for RTP packets.\"\"\"\r\n\t\twhile True:\r\n\t\t\ttry:\r\n\t\t\t\tdata = self.rtpSocket.recv(20480)\r\n\t\t\t\tif data:\r\n\t\t\t\t\trtpPacket = RtpPacket()\r\n\t\t\t\t\trtpPacket.decode(data)\r\n\t\t\t\t\t\r\n\t\t\t\t\tcurrFrameNbr = rtpPacket.seqNum()\r\n\t\t\t\t\t\r\n\t\t\t\t\tif self.prev_datarate==None:\r\n\t\t\t\t\t\tself.prev_datarate=time()\r\n\r\n\t\t\t\t\tself.video_current_data_rate=int(sys.getsizeof(rtpPacket.getPayload())/(time()-self.prev_datarate)/1000)\r\n\t\t\t\t\tprint(\"Current Seq Num: \" + str(currFrameNbr)+' '+str(self.video_current_data_rate))\r\n\t\t\t\t\tself.prev_datarate=time()\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\tif currFrameNbr > self.frameNbr: # Discard the late packet\r\n\t\t\t\t\t\tself.frameNbr = currFrameNbr\r\n\t\t\t\t\t\tself.updateMovie(self.writeFrame(rtpPacket.getPayload()))\r\n\t\t\texcept:\r\n\t\t\t\t# Stop listening upon requesting PAUSE or TEARDOWN\r\n\t\t\t\tif self.playEvent.isSet(): \r\n\t\t\t\t\tbreak\r\n\t\t\t\t\r\n\t\t\t\t# Upon receiving ACK for TEARDOWN request,\r\n\t\t\t\t# close the RTP socket\r\n\t\t\t\tif self.teardownAcked == 1:\r\n\t\t\t\t\tself.rtpSocket.shutdown(socket.SHUT_RDWR)\r\n\t\t\t\t\tself.rtpSocket.close()\r\n\t\t\t\t\tbreak\r\n\t\t\t\t\t\r\n\tdef writeFrame(self, data):\r\n\t\t\"\"\"Write the received frame to a temp image file. Return the image file.\"\"\"\r\n\t\tcachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT\r\n\t\tfile = open(cachename, \"wb\")\r\n\t\tfile.write(data)\r\n\t\tfile.close()\r\n\t\t\r\n\t\treturn cachename\r\n\t\r\n\tdef updateMovie(self, imageFile):\r\n\t\t\"\"\"Update the image file as video frame in the GUI.\"\"\"\r\n\t\tself.current_fps=0\r\n\t\tif self.prev_fps == None:\r\n \t\t\tself.prev_fps=time()\r\n\t\telse:\r\n\t\t\t\tself.current_fps=round(1/(time()-self.prev_fps),2)\r\n\t\t\t\tself.prev_fps=time()\r\n\t\timg=Image.open(imageFile)\r\n\t\tdraw = ImageDraw.Draw(img)\r\n\t\tdraw.text((5, 5),\"fps: \"+str(self.current_fps),(255,255,255))\r\n\t\tphoto = ImageTk.PhotoImage(img)\r\n\t\tself.label.configure(image = photo, height=288) \r\n\t\tself.label.image = photo\r\n\t\t\r\n\tdef connectToServer(self):\r\n\t\t\"\"\"Connect to the Server. Start a new RTSP/TCP session.\"\"\"\r\n\t\tself.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\t\ttry:\r\n\t\t\tself.rtspSocket.connect((self.serverAddr, self.serverPort))\r\n\t\texcept:\r\n\t\t\ttkMessageBox.showwarning('Connection Failed', 'Connection to \\'%s\\' failed.' %self.serverAddr)\r\n\t\r\n\tdef sendRtspRequest(self, requestCode):\r\n\t\t\"\"\"Send RTSP request to the server.\"\"\"\t\r\n\t\t#-------------\r\n\t\t# TO COMPLETE\r\n\t\t#-------------\r\n\t\t\r\n\t\t# Setup request\r\n\t\tif requestCode == self.SETUP:\r\n\t\t\tself.rtpSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\r\n\t\t\tthreading.Thread(target=self.recvRtspReply).start()\r\n\t\t\t# Update RTSP sequence number.\r\n\t\t\t# ...\r\n\t\t\tself.rtspSeq = 1\r\n\t\t\t\r\n\t\t\t# Write the RTSP request to be sent.\r\n\t\t\t# request = ...\r\n\t\t\trequest = \"SETUP \" + str(self.fileName) + \" RTSP/1.0\\nCSeq: \" + str(self.rtspSeq) + \"\\nTransport: RTP/UDP; client_port= \" + str(self.rtpPort)\r\n\t\t\tself.rtspSocket.send(request.encode(\"utf-8\"))\r\n\t\t\t# Keep track of the sent request.\r\n\t\t\t# self.requestSent = ...\r\n\t\t\tself.requestSent = self.SETUP\r\n\t\t\r\n\t\t# Play request\r\n\t\telif requestCode == self.PLAY:\r\n\t\t\t# Update RTSP sequence number.\r\n\t\t\t# ...\r\n\t\t\tself.rtspSeq = self.rtspSeq + 1\r\n\t\t\t\r\n\t\t\t# Write the RTSP request to be sent.\r\n\t\t\t# request = ...\r\n\t\t\trequest = \"PLAY \" + str(self.fileName) + \" RTSP/1.0\\nCSeq: \" + str(self.rtspSeq) +\"\\nSession: \" + str(self.sessionId)\r\n\t\t\tself.rtspSocket.send(request.encode(\"utf-8\"))\r\n\t\t\t# Keep track of the sent request.\r\n\t\t\t# self.requestSent = ...\r\n\t\t\tself.requestSent = self.PLAY\r\n\t\t# Pause request\r\n\t\telif requestCode == self.PAUSE:\r\n\t\t\t# Update RTSP sequence number.\r\n\t\t\t# ...\r\n\t\t\tself.rtspSeq = self.rtspSeq + 1\r\n\t\t\t\r\n\t\t\t# Write the RTSP request to be sent.\r\n\t\t\t# request = ...\r\n\t\t\trequest = \"PAUSE \" + str(self.fileName) + \" RTSP/1.0\\nCSeq: \" + str(self.rtspSeq) + \"\\nSession: \" + str(self.sessionId)\r\n\t\t\tself.rtspSocket.send(request.encode(\"utf-8\"))\r\n\t\t\t# Keep track of the sent request.\r\n\t\t\t# self.requestSent = ...\r\n\t\t\tself.requestSent = self.PAUSE\r\n\t\t# Teardown request\r\n\t\telif requestCode == self.TEARDOWN and not self.state == self.INIT:\r\n\t\t\t# Update RTSP sequence number.\r\n\t\t\t# ...\r\n\t\t\tself.rtspSeq = self.rtspSeq + 1\r\n\t\t\t# Write the RTSP request to be sent.\r\n\t\t\t# request = ...\r\n\t\t\trequest = \"TEARDOWN \" + str(self.fileName) + \" RTSP/1.0\\nCSeq: \" + str(self.rtspSeq) + \"\\nSession: \" + str(self.sessionId)\r\n\t\t\tself.rtspSocket.send(request.encode(\"utf-8\"))\r\n\t\t\t# Keep track of the sent request.\r\n\t\t\t# self.requestSent = ...\r\n\t\t\tself.requestSent = self.TEARDOWN\r\n\t\telif requestCode == self.REPLAY and not self.state == self.INIT:\r\n\t\t\tself.rtspSeq = self.rtspSeq + 1\r\n\t\t\trequest = \"REPLAY \" + str(self.fileName) + \" RTSP/1.0\\nCSeq: \" + str(self.rtspSeq) + \"\\nSession: \" + str(self.sessionId)\r\n\t\t\tself.rtspSocket.send(request.encode(\"utf-8\"))\r\n\t\t\tself.requestSent = self.REPLAY\r\n\t\telif requestCode == self.DESCRIBE and not self.state == self.INIT:\r\n\t\t\tself.rtspSeq = self.rtspSeq + 1\r\n\t\t\trequest = \"DESCRIBE \" + str(self.fileName) + \" RTSP/1.0\\nCSeq: \" + str(self.rtspSeq) + \"\\nSession: \" + str(self.sessionId)\r\n\t\t\tself.rtspSocket.send(request.encode(\"utf-8\"))\r\n\t\t\tself.requestSent = self.DESCRIBE\r\n\t\telif requestCode == self.SPEED and not self.state == self.INIT:\r\n\t\t\tself.rtspSeq = self.rtspSeq + 1\r\n\t\t\trequest = \"SPEED \" + str(self.fileName) + \" RTSP/1.0\\nCSeq: \" + str(self.rtspSeq) + \"\\nSession: \" + str(self.sessionId)\r\n\t\t\tself.rtspSocket.send(request.encode(\"utf-8\"))\r\n\t\t\tself.requestSent = self.SPEED\r\n\t\telse:\r\n\t\t\treturn\r\n\t\t\r\n\t\t# Send the RTSP request using rtspSocket.\r\n\t\t# ...\r\n\t\t\r\n\t\tprint('\\nData sent:\\n' + request)\r\n\t\r\n\tdef recvRtspReply(self):\r\n\t\t\"\"\"Receive RTSP reply from the server.\"\"\"\r\n\t\twhile True:\r\n\t\t\treply = self.rtspSocket.recv(1024)\r\n\t\t\t\r\n\t\t\tif reply: \r\n\t\t\t\tself.parseRtspReply(reply.decode(\"utf-8\"))\r\n\t\t\t\r\n\t\t\t# Close the RTSP socket upon requesting Teardown\r\n\t\t\tif self.requestSent == self.TEARDOWN:\r\n\t\t\t\tself.rtspSocket.shutdown(socket.SHUT_RDWR)\r\n\t\t\t\tself.rtspSocket.close()\r\n\t\t\t\tbreak\r\n\t\r\n\tdef parseRtspReply(self, data):\r\n\t\t\"\"\"Parse the RTSP reply from the server.\"\"\"\r\n\t\tprint(\"-\"*40 + \"\\nData received:\\n\" + data)\r\n\t\tlines = data.split('\\n')\r\n\t\tseqNum = int(lines[1].split(' ')[1])\r\n\r\n\t\t# Process only if the server reply's sequence number is the same as the request's\r\n\t\tif seqNum == self.rtspSeq:\r\n\t\t\tsession = int(lines[2].split(' ')[1])\r\n\t\t\t# New RTSP session ID\r\n\t\t\tif self.sessionId == 0:\r\n\t\t\t\tself.sessionId = session\r\n\t\t\t\r\n\t\t\t# Process only if the session ID is the same\r\n\t\t\tif self.sessionId == session:\r\n\t\t\t\tif int(lines[0].split(' ')[1]) == 200: \r\n\t\t\t\t\tif self.requestSent == self.SETUP:\r\n\t\t\t\t\t\t#-------------\r\n\t\t\t\t\t\t# TO COMPLETE\r\n\t\t\t\t\t\t#-------------\r\n\t\t\t\t\t\t# Update RTSP state.\r\n\t\t\t\t\t\t# self.state = ...\r\n\t\t\t\t\t\tself.state = self.READY\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Open RTP port.\r\n\t\t\t\t\t\tself.openRtpPort() \r\n\t\t\t\t\t\tself.playMovie()\r\n\t\t\t\t\telif self.requestSent == self.PLAY:\r\n\t\t\t\t\t\t# self.state = ...\r\n\t\t\t\t\t\tself.state = self.PLAYING\r\n\t\t\t\t\telif self.requestSent == self.PAUSE:\r\n\t\t\t\t\t\t# self.state = ...\r\n\t\t\t\t\t\tself.state = self.READY\r\n\t\t\t\t\t\t# The play thread exits. A new thread is created on resume.\r\n\t\t\t\t\t\tself.playEvent.set()\r\n\t\t\t\t\telif self.requestSent == self.REPLAY:\r\n\t\t\t\t\t\t# self.state = ...\r\n\t\t\t\t\t\tself.state = self.READY\r\n\t\t\t\t\t\t# The play thread exits. A new thread is created on resume.\r\n\t\t\t\t\t\tself.playEvent.set()\r\n\t\t\t\t\t\tself.playMovie()\r\n\t\t\t\t\telif self.requestSent == self.TEARDOWN:\r\n\t\t\t\t\t\t# self.state = ...\r\n\t\t\t\t\t\tself.state = self.INIT\r\n\t\t\t\t\t\t# Flag the teardownAcked to close the socket.\r\n\t\t\t\t\t\tself.teardownAcked = 1\r\n\t\t\t\t\telif self.requestSent == self.DESCRIBE:\r\n\t\t\t\t\t\t# self.state = ...\r\n\t\t\t\t\t\tself.state = self.READY\r\n\t\t\t\t\t\t# The play thread exits. A new thread is created on resume.\r\n\t\t\t\t\t\tself.playEvent.set()\r\n\t\t\t\t\t\ttkMessageBox.showinfo(title='Information', message='File name: '+self.fileName+'\\n'+data.split('\\n')[2]+'\\nFPS: '+str(self.current_fps)+'\\nVideo Data Rate: '+str(self.video_current_data_rate)+' kBytes')\r\n\t\t\t\t\telif self.requestSent == self.SPEED:\r\n\t\t\t\t\t\tif self.speed_idx==6:\r\n\t\t\t\t\t\t\tself.speed_idx=0\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tself.speed_idx+=1\r\n\t\t\t\t\t\tself.speed[\"text\"] = self.speed_arr[self.speed_idx]\r\n\t\r\n\tdef openRtpPort(self):\r\n\t\t\"\"\"Open RTP socket binded to a specified port.\"\"\"\r\n\t\t#-------------\r\n\t\t# TO COMPLETE\r\n\t\t#-------------\r\n\t\t# Create a new datagram socket to receive RTP packets from the server\r\n\t\t# self.rtpSocket = ...\r\n\t\tself.rtpSocket.settimeout(0.5)\r\n\t\t# Set the timeout value of the socket to 0.5sec\r\n\t\t# ...\r\n\t\t\r\n\t\ttry:\r\n\t\t\t# Bind the socket to the address using the RTP port given by the client user\r\n\t\t\t# ...\r\n\t\t\tself.rtpSocket.bind((\"\",self.rtpPort))\r\n\t\texcept:\r\n\t\t\ttkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort)\r\n\r\n\tdef handler(self):\r\n\t\t\"\"\"Handler on explicitly closing the GUI window.\"\"\"\r\n\t\tself.pauseMovie()\r\n\t\tif tkMessageBox.askokcancel(\"Quit?\", \"Are you sure you want to quit?\"):\r\n\t\t\tself.exitClient()\r\n\t\telse: # When the user presses cancel, resume playing.\r\n\t\t\tself.playMovie()\r\n","repo_name":"sangngoc27042001/Computer-Network-Assignment-1","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":12931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"23804113355","text":"import logging\nimport sys\n\nfrom cacofonisk import AmiRunner, LoggingReporter\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nlog_handler = logging.StreamHandler(sys.stdout)\nlog_handler.setLevel(logging.INFO)\nlog_formatter = logging.Formatter(\n '%(asctime)s %(name)s: %(levelname)s: %(message)s')\nlog_handler.setFormatter(log_formatter)\nlogger.addHandler(log_handler)\n\n\nreporter = LoggingReporter()\n# Attach the AmiRunner to the specified Asterisk.\nrunner = AmiRunner([\n 'tcp://cacofonisk:bard@127.0.0.1:5038',\n], reporter, logger=logger)\nrunner.run()\n","repo_name":"VoIPGRID/cacofonisk","sub_path":"examples/amirunner.py","file_name":"amirunner.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"80"} +{"seq_id":"71360286658","text":"class Node:\n def __init__(self, data, next = None):\n self.data = data\n self.next = next\n\nclass Stack:\n def __init__(self):\n self.count = 0\n self.top = None\n\n def push(self, data):\n node = Node(data)\n if self.top:\n node.next = self.top\n self.top = node\n self.count += 1\n\n def pop(self):\n pushing = self.top.data\n self.top = self.top.next\n self.count -= 1\n return pushing\n\n def show(self):\n print(self.top.data)\n\nsta4ka = Stack()\nsta4ka.push(4)\nsta4ka.push(8)\nsta4ka.push(12)\nprint(4, 8, 12)\nsta4ka.show()\nprint(\"count = \", sta4ka.count)\nprint(\"pop \", sta4ka.pop())\nprint(\"pop \", sta4ka.pop())\nprint(\"count = \", sta4ka.count)\nprint(sta4ka.top.data)","repo_name":"Dimazick/StackAndQuequePythonHomework","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"41744541121","text":"\n\n#import necessary libraries\nfrom googletrans import Translator\n\n#get the text to be translated and the language to translate to\ntext = input('Enter the text to be translated: ')\nlanguage = input('Enter the language to translate to: ')\n\n#create the translator object\ntranslator = Translator()\n\n#translate the text\ntranslation = translator.translate(text, dest=language).text\n\n#get the file name from the user\nfilename = input('Enter the file name for the translation: ')\n\n#open the file and write the translation to it\nwith open(filename, 'w', encoding='utf-8') as f:\n f.write(translation)","repo_name":"DigitalKhalid/Python-Automations","sub_path":"Text-Translation.py","file_name":"Text-Translation.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26445655692","text":"import random\nimport time\n#vraag\nhvlMM = int(input(\"hoeveel kleuren MM's moet er worden toegevoegd aan de zak?\"))\n \n#kleuren\nKleurMM = [\"oranje\", \"blauw\", \"groen\", \"bruin\"]\n\n#waarde\noranje = 0\nblauw = 0\ngroen = 0\nbruin = 0\n\nmnmDictionaryBag = {\n \"rood\": 2,\n \"geel\": 5,\n \"bruin\": 10\n}\n\ndef MMzakje(Aantal):\n global oranje\n global blauw\n global groen\n global bruin\n mm = 1\n while mm <= Aantal:\n MMrandom = random.choice(KleurMM)\n if MMrandom == \"oranje\":\n oranje += 1\n elif MMrandom == \"blauw\":\n blauw += 1\n elif MMrandom == \"groen\": \n groen += 1 \n elif MMrandom == \"bruin\":\n bruin += 1\n mm += 1\n print(\"Inhoud van de zak:\")\n time.sleep(2)\n print(\" oranje\", str(oranje), \"\\n blauw\", str(blauw), \"\\n groen: \", str(groen), \"\\n bruin\", str(bruin))\nMMzakje(hvlMM)\n\n","repo_name":"emkse/collections","sub_path":"M&M.py","file_name":"M&M.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39024956493","text":"APP_HEIGHT = 800\nAPP_WIDTH = 1200\n\nMAP_WIDTH = APP_WIDTH\nMAP_HEIGHT = APP_HEIGHT\n\nrgb2hex = lambda r,g,b: f\"#{r:02x}{g:02x}{b:02x}\"\n\nMAP_BG = rgb2hex(117, 245, 66)\nSTART_MARGIN = (50, 50)\n\nMAX_SNAKE_SIZE = 30\n\nBASE_SPEED = 10\n\n\nSTART_DELAY = 600\nSTART_LOOP_DELAY = 60\nMIN_LOOP_DELAY = 8\nLOOP_DELAY_DECREASE_TIME = 200","repo_name":"slevi123/snake","sub_path":"gconsts.py","file_name":"gconsts.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"9455938593","text":"#!/usr/bin/python\n\nimport os\nimport pfpd_const as protocol\n\nEXTRACT_MODEL = os.path.join(protocol.ROSETTA_BIN, 'extract_pdbs.linuxgccrelease') + \\\n ' -database ' + protocol.ROSETTA_DB + ' @extract_flags > log'\n\n\ndef extracting_flags(lowest_sc_struct):\n with open('extract_flags', 'w') as extract:\n extract.write('-in:file:silent decoys.silent\\n'\n '-in:file:tags {}\\n'.format(lowest_sc_struct))\n\n\ndef extract_pdb():\n with open('score.sc', 'r') as score_file:\n scores = score_file.readlines()\n header = scores[1].split()\n scores = scores[2:] # SEQUENCE line + header\n reweighted_column = header.index('reweighted_sc')\n description_column = header.index('description')\n\n sorted_sc = sorted(scores, key=lambda sc_line: float(sc_line.split()[reweighted_column]))\n lowest_sc_struct = sorted_sc[0].split()[description_column]\n extracting_flags(lowest_sc_struct)\n os.system(EXTRACT_MODEL)\n\nif __name__ == \"__main__\":\n extract_pdb()\n","repo_name":"mattfeng/rosetta-tools","sub_path":"peptide_docking/extract_top_model.py","file_name":"extract_top_model.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"26014367993","text":"import torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets,transforms\nimport torch.utils.data as D\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\nimport time\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom BinarisedNetwork import *\nimport BinarisedUtil\n\n\n\n\n\n\n\n\ntrain_set = datasets.MNIST('./data', train=True, download=True,\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\ntrain_loader = D.DataLoader(train_set,batch_size=10,shuffle=True)\n\ntest_set = datasets.MNIST('./data', train=False, download=True,\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\ntest_loader = D.DataLoader(test_set,batch_size=10,shuffle=True)\n\n\nclass Network(nn.Module):\n def __init__(self):\n super(Network, self).__init__()\n self.layers = nn.Sequential(\n nn.Flatten(),\n BinaryLinear(in_features=1*28*28, out_features=1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n # First Hidden layer\n BinaryLinear(in_features=1024, out_features=1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n # Second Hidden layer\n BinaryLinear(in_features=1024, out_features=1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n # Third Hidden layer\n BinaryLinear(in_features=1024, out_features=1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(),\n\n BinaryLinear(in_features=1024, out_features=10),\n nn.LogSoftmax()\n )\n\n def forward(self, x):\n return self.layers(x)\n\nnetwork = Network()\nprint(network)\n\n# Decalring the optimizer\noptimizer = optim.Adam(network.parameters(), lr=0.001)\ncriterion = nn.CrossEntropyLoss()\nbinarisation = BinarisedUtil.BinarisedUtil(network)\n\n\ndef train(epoch):\n network.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n\n data, target = Variable(data), Variable(target)\n optimizer.zero_grad()\n\n binarisation.Binarization()\n\n output = network(data)\n loss = criterion(output, target)\n loss.backward()\n\n binarisation.Restore()\n binarisation.UpdateBinaryGradWeight()\n\n optimizer.step()\n if batch_idx % 100 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.data.item()))\n\n\n\naccur = []\n\n\ndef test():\n network.eval()\n test_loss = 0\n correct = 0\n\n binarisation.Binarization()\n for data, target in test_loader:\n\n data, target = Variable(data, volatile=True), Variable(target)\n output = network(data)\n test_loss += criterion(output, target).data.item() # sum up batch loss\n pred = output.data.max(1, keepdim=True).item() # get the index of the max log-probability\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n binarisation.Restore()\n\n a = 100. * correct / len(test_loader.dataset)\n accur.append(a)\n test_loss /= len(test_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\ndef timeSince(since):\n now = time.time()\n s = now - since\n\n return s\n\nstart = time.time()\ntime_graph=[]\ne=[]\ntorch.manual_seed(42)\nfor epoch in range(1, 10):\n e.append(epoch)\n train(epoch)\n seco=timeSince(start)\n time_graph.append(seco)\n test()\n\nprint(time_graph)\nplt.title('epoch per time', fontsize=20)\nplt.ylabel('time (s)')\nplt.plot(e,time_graph)\nplt.show()\nplt.title('Accuracy With epoch', fontsize=20)\nplt.plot(e,accur)\nplt.show()\n","repo_name":"noureddinekhiati/XNOR_NET","sub_path":"Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"5147023957","text":"################################################################################\n# oops/hosts/hst/acs/sbc.py: HST/ACS subclass SBC\n################################################################################\n\ntry:\n import astropy.io.fits as pyfits\nexcept ImportError:\n import pyfits\nfrom . import ACS\n\n################################################################################\n# Standard class methods\n################################################################################\n\ndef from_file(filespec, **parameters):\n \"\"\"A general, static method to return an Observation object based on a given\n data file generated by HST/ACS/SBC.\n \"\"\"\n\n # Open the file\n hst_file = pyfits.open(filespec)\n\n # Make an instance of the SBC class\n this = SBC()\n\n # Confirm that the telescope is HST\n if this.telescope_name(hst_file) != \"HST\":\n raise IOError(\"not an HST file: \" + this.filespec(hst_file))\n\n # Confirm that the instrument is ACS\n if this.instrument_name(hst_file) != \"ACS\":\n raise IOError(\"not an HST/ACS file: \" + this.filespec(hst_file))\n\n # Confirm that the detector is SBC\n if this.detector_name(hst_file) != \"SBC\":\n raise IOError(\"not an HST/ACS/SBC file: \" + this.filespec(hst_file))\n\n return SBC.from_opened_fitsfile(hst_file, **parameters)\n\nIDC_DICT = None\n\nGENERAL_SYN_FILES = [\"OTA/hst_ota_???_syn.fits\",\n \"ACS/acs_sbc_mama_???_syn.fits\"]\n\nFILTER_SYN_FILE = [\"ACS/acs_\", \"_???_syn.fits\"]\n\n#===============================================================================\n#===============================================================================\nclass SBC(ACS):\n \"\"\"This class defines functions and properties unique to the NIC1 detector.\n Everything else is inherited from higher levels in the class hierarchy.\n\n Objects of this class are empty; they only exist to support inheritance.\n \"\"\"\n\n def define_fov(self, hst_file, **parameters):\n \"\"\"An FOV object defining the field of view of the given image file.\"\"\"\n\n global IDC_DICT\n\n # Load the dictionary of IDC parameters if necessary\n if IDC_DICT is None:\n IDC_DICT = self.load_idc_dict(hst_file, (\"FILTER1\",))\n\n # Define the key into the dictionary\n idc_key = (hst_file[0].header[\"FILTER1\"],)\n\n # Use the default function defined at the HST level for completing the\n # definition of the FOV\n return self.construct_fov(IDC_DICT[idc_key], hst_file)\n\n #===========================================================================\n def filter_name(self, hst_file, layer=None):\n \"\"\"The name of the filter for this particular ACS detector.\"\"\"\n\n return hst_file[0].header[\"FILTER1\"]\n\n #===========================================================================\n def select_syn_files(self, hst_file, **parameters):\n \"\"\"The list of SYN files containing profiles that are to be multiplied\n together to obtain the throughput of the given instrument, detector, and\n filter combination.\n \"\"\"\n\n # Copy all the standard file names\n syn_filenames = []\n for filename in GENERAL_SYN_FILES:\n syn_filenames.append(filename)\n\n # Add the filter file name\n syn_filenames.append(FILTER_SYN_FILE[0] +\n hst_file[0].header[\"FILTER1\"].lower() +\n FILTER_SYN_FILE[1])\n\n return syn_filenames\n\n #===========================================================================\n @staticmethod\n def from_opened_fitsfile(hst_file, **parameters):\n \"\"\"A general class method to return an Observation object based on an\n HST data file generated by HST/ACS/SBC.\n \"\"\"\n\n return SBC().construct_snapshot(hst_file, **parameters)\n\n################################################################################\n","repo_name":"SETI/rms-oops","sub_path":"oops/hosts/hst/acs/sbc.py","file_name":"sbc.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"16188252610","text":"from django.urls import path\nfrom . import views\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('blog/', views.post_list, name='post_list'),\n path('blog//', views.post_detail, name='post_detail'),\n path('contact/', views.contact_page, name = 'contact_page'),\n # path('post//comment/', views.add_comment_to_post, name='add_comment_to_post'),\n]","repo_name":"Krandheer/poetry","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"34874574322","text":"# Third-party\nimport astropy.units as u\nimport numpy as np\n\n# Package\nfrom ..likelihood import design_matrix, tensor_vector_scalar, marginal_ln_likelihood\n\nfrom .helpers import FakeData\n\n\nclass TestLikelihood(object):\n\n # TODO: repeated code\n def truths_to_nlp(self, truths):\n # P, M0, ecc, omega\n P = truths['P'].to(u.day).value\n M0 = truths['M0'].to(u.radian).value\n ecc = truths['e']\n omega = truths['omega'].to(u.radian).value\n return np.array([P, M0, ecc, omega, 0.])\n\n def setup(self):\n d = FakeData()\n self.datasets = d.datasets\n self.params = d.params\n self.truths = d.truths\n\n def test_design_matrix(self):\n\n data = self.datasets['binary']\n nlp = self.truths_to_nlp(self.truths['binary'])\n A = design_matrix(nlp, data, self.params['binary'])\n assert A.shape == (len(data), 2) # K, v0\n assert np.allclose(A[:,1], 1)\n\n # TODO: triple disabled\n # nlp = self.truths_to_nlp(self.truths['triple'])\n # A = design_matrix(nlp, data, self.params['triple'])\n # assert A.shape == (len(data), 3) # K, v0, v1\n # assert np.allclose(A[:,1], 1)\n # assert np.allclose(A[:,2], data._t_bmjd)\n\n def test_tensor_vector_scalar(self):\n\n data = self.datasets['binary']\n nlp = self.truths_to_nlp(self.truths['binary'])\n A = design_matrix(nlp, data, self.params['binary'])\n ATCinvA, p, chi2 = tensor_vector_scalar(A, data.ivar.value,\n data.rv.value)\n true_p = [self.truths['binary']['K'].value,\n self.truths['binary']['v0'].value]\n assert np.allclose(p, true_p, rtol=1e-2)\n\n # --\n\n # TODO: triple disabled\n # data = self.data['triple']\n # nlp = self.truths_to_nlp(self.truths['triple'])\n # A = design_matrix(nlp, data, self.params['triple'])\n # ATCinvA, p, chi2 = tensor_vector_scalar(A, data.ivar.value,\n # data.rv.value)\n #\n # true_p = [self.truths['triple']['K'].value, self.fd.v0.value, self.fd.v1.value]\n # assert np.allclose(p, true_p, rtol=1e-2)\n\n def test_marginal_ln_likelihood_P(self):\n \"\"\"\n Check that the true period is the maximum likelihood period\n \"\"\"\n data = self.datasets['circ_binary']\n params = self.params['circ_binary']\n true_nlp = self.truths_to_nlp(self.truths['circ_binary'])\n # print('ln_like', marginal_ln_likelihood(true_nlp, data, params))\n\n vals = np.linspace(true_nlp[0]-1., true_nlp[0]+1, 4096)\n lls = np.zeros_like(vals)\n for i,val in enumerate(vals):\n nlp = true_nlp.copy()\n nlp[0] = val\n lls[i] = marginal_ln_likelihood(nlp, data, params)\n\n assert np.allclose(true_nlp[0], vals[lls.argmax()], rtol=1E-4)\n\n def test_marginal_ln_likelihood_P_samples(self):\n \"\"\"\n This test is a little crazy. We generate samples in P, M0\n \"\"\"\n\n data = self.datasets['circ_binary']\n params = self.params['circ_binary']\n true_nlp = self.truths_to_nlp(self.truths['circ_binary'])\n\n n_samples = 16384\n P = np.random.uniform(true_nlp[0] - 2., true_nlp[0] + 2., size=n_samples)\n M0 = np.random.uniform(0, 2*np.pi, size=n_samples)\n\n lls = np.zeros_like(P)\n n_neg = 0\n for i in range(n_samples):\n nlp = true_nlp.copy()\n nlp[0] = P[i]\n nlp[1] = M0[i]\n lls[i] = marginal_ln_likelihood(nlp, data, params)\n\n A = design_matrix(nlp, data, params)\n _,p,_ = tensor_vector_scalar(A, data.ivar.value, data.rv.value)\n if p[0] < 0:\n n_neg += 1\n\n # rejection sample using the marginal likelihood\n uu = np.random.uniform(size=n_samples)\n idx = uu < np.exp(lls - lls.max())\n print(\"{} good samples\".format(idx.sum()))\n\n assert idx.sum() > 1\n assert np.std(P[idx]) < 1.\n\n # import matplotlib.pyplot as plt\n\n # plt.figure()\n # bins = np.linspace(true_nlp[0] - 2., true_nlp[0] + 2., 32)\n # plt.hist(P, bins=bins, alpha=0.25, normed=True)\n # plt.hist(P[idx], bins=bins, alpha=0.4, normed=True)\n # plt.axvline(true_nlp[0], color='r')\n\n # plt.figure()\n # bins = np.linspace(0, 2*np.pi, 32)\n # plt.hist(M0, bins=bins, alpha=0.25, normed=True)\n # plt.hist(M0[idx], bins=bins, alpha=0.4, normed=True)\n # plt.axvline(true_nlp[1], color='r')\n\n # plt.show()\n","repo_name":"megbedell/thejoker","sub_path":"thejoker/sampler/tests/test_likelihood.py","file_name":"test_likelihood.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"80"} +{"seq_id":"8713536249","text":"import pickle as pk\nimport numpy as np\nimport pandas as pd\nimport subprocess\nfrom corpus_utils import PatentCorpus\nfrom plot_utils import plot_score_distr, calc_simcoef_distr, group_combis, calc_auc\n\ndef make_input_file(dir_name='/home/lea/Documents/master_thesis/patent_search/database/human_eval/patent_sheets/*'):\n \"\"\"\n Iterate over patents in single_pat_corpus and write into a dataframe that is then stored in a csv\n \"\"\"\n # load patent corpus\n pat_corpus = PatentCorpus()\n pat_corpus.mode = 'wmd'\n # ugly hack to invoke __iter__() function :-( :\n list(pat_corpus)\n single_pat_corpus = pat_corpus.single_pat_corpus\n # make empty data frame\n df = pd.DataFrame(columns=['id', 'text'])\n # go through single_pat_corpus and fill data frame\n for pid, text in single_pat_corpus.items():\n df = df.append({'id': pid, 'text': text}, ignore_index=True)\n df.to_csv('human_eval/wmd_pat_corpus.txt', sep='\\t', header=False, index=False, encoding='utf-8')\n\nif __name__ == \"__main__\":\n #make_input_file()\n dist_mat = pk.load(open('/home/lea/Documents/master_thesis/patent_search/wmd-master/dist_matrix.pk'))\n vectors = pk.load(open('/home/lea/Documents/master_thesis/patent_search/wmd-master/vectors.pk'))\n id_list = list(vectors[3])\n combis = np.load('human_eval/corpus_info/combis.npy')\n binary_label_pairs = np.load('human_eval/corpus_info/binary_label_pairs.npy').item()\n human_label_pairs = np.load('human_eval/corpus_info/human_label_pairs.npy').item()\n binary_sim_combis, binary_diff_combis = group_combis(binary_label_pairs)\n human_sim_combis, human_diff_combis = group_combis(human_label_pairs)\n binary_scores = {}\n human_scores = {}\n binary_scores['cited'] = []\n binary_scores['random'] = []\n human_scores['relevant'] = []\n human_scores['not relevant'] = []\n for combi in binary_sim_combis:\n i = id_list.index(combi[0])\n j = id_list.index(combi[1])\n binary_scores['cited'].append(dist_mat[i,j])\n for combi in binary_diff_combis:\n i = id_list.index(combi[0])\n j = id_list.index(combi[1])\n binary_scores['random'].append(dist_mat[i,j])\n for combi in human_sim_combis:\n i = id_list.index(combi[0])\n j = id_list.index(combi[1])\n human_scores['relevant'].append(dist_mat[i,j])\n for combi in human_diff_combis:\n i = id_list.index(combi[0])\n j = id_list.index(combi[1])\n human_scores['not relevant'].append(dist_mat[i,j])\n binary_auc = calc_auc(binary_scores['cited'], binary_scores['random'])[2]\n human_auc = calc_auc(human_scores['relevant'], human_scores['not relevant'])[2]\n plot_score_distr('human_eval', 'linear', ['cited', 'random'], \n {'cited': binary_scores['cited'], 'random': binary_scores['random']},\n binary_auc, ['cited'], histdir='wmd', bins=50)\n plot_score_distr('human_eval', 'linear', ['relevant', 'not relevant'], \n {'relevant': human_scores['relevant'], 'not relevant': human_scores['not relevant']},\n human_auc, ['relevant'], histdir='wmd', bins=50)","repo_name":"helmersl/patent_similarity_search","sub_path":"wmd_pats.py","file_name":"wmd_pats.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"80"} +{"seq_id":"2177968738","text":"from setuptools import setup, find_packages\nimport jacobsjsondoc._version as _version\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ninstall_requires = []\nwith open(\"requirements.txt\", \"r\") as fh:\n install_requires = [ x for x in fh.read().split(\"\\n\") if len(x) > 0 ]\n\nsetup(\n name=\"jacobs-json-doc\",\n version=_version.__version__,\n description='A JSON/YAML loader',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author=\"Jacob Brunson\",\n author_email=\"pypi@jacobbrunson.com\",\n url=\"https://github.com/pearmaster/jacobs-json-doc\",\n license='GPLv2',\n packages=find_packages(),\n install_requires=install_requires,\n keywords='conversion',\n classifiers= [\n \"Programming Language :: Python :: 3\",\n ],\n python_requires='>=3.7',\n)","repo_name":"pearmaster/jacobs-json-doc","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"43565068735","text":"v = 0; \nc= 0; \nstr = \"gopal\"; \na = str.lower(); \nfor i in range(0,len(a)): \n if str[i] in ('a',\"e\",\"i\",\"o\",\"u\"): \n v = v + 1; \n else: \n c = c + 1; \nprint(\"Total number of vowel and consonant are\" ); \nprint(v); \nprint(c); \n","repo_name":"Devprasanna1905/python","sub_path":"vowels and consonants in string.py","file_name":"vowels and consonants in string.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"10375391436","text":"from torch.utils.data import Dataset\nimport torchvision.transforms as T\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom matplotlib import image\nimport torch.nn.functional as F\n\n\nclass ImageDataset(Dataset):\n def __init__(self,csv, img_folder,transform):\n self.csv = csv\n self.transform = transform\n self.img_folder = img_folder\n self.bands = [\"B2\",\"B3\",\"B4\"]\n #get all Data with unspin\n\n\n self.image_names = self.csv[:]['id']\n self.dates = self.csv[:]['date']\n self.quality = self.csv[:]['quality']\n self.labels=self.csv[:]['label']\n \n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.image_names)\n \n def __getitem__(self, index):\n 'Generates one sample of data'\n #Select Sample\n imgArr = []\n ImgCropTransform = T.Compose([T.ToPILImage(),T.Resize((40,40)),T.ToTensor()])\n for band in self.bands:\n path = f'{self.img_folder}/{self.image_names[index]}-{self.dates[index]}-{band}.jpg'\n imgArr.append(image.imread(path))\n\n stacked = (np.dstack((imgArr[0],imgArr[1],imgArr[2]))).astype(np.uint8)\n stacked = ImgCropTransform(stacked)\n stacked = stacked[:,20:40,10:30]\n item:torch.Tensor = self.transform(stacked)\n \n target = int(self.labels[index])\n if(target==2):\n target = 1\n return item, target\n\nclass BaseModel(nn.Module):\n def __init__(self, features = 20):\n super().__init__()\n self.features = features\n self.conv1 = nn.Conv2d(3, features, kernel_size=3, padding=1)\n self.conv1_batchnorm = nn.BatchNorm2d(num_features=features)\n self.conv2 = nn.Conv2d(features, features//2, kernel_size=3, padding=1)\n self.conv2_batchnorm = nn.BatchNorm2d(num_features=features//2)\n self.fc1 = nn.Linear((features//2) * (10) *(10), 50)\n self.fc2 = nn.Linear(50, 2)\n def forward(self, x):\n out = self.conv1_batchnorm(self.conv1(x))\n out = F.max_pool2d(torch.tanh(out), 2)\n out = self.conv2_batchnorm(self.conv2(out))\n out = F.max_pool2d(torch.tanh(out), 2)\n out = out.view(-1, (self.features//2) * (10) *(10))\n out = torch.tanh(self.fc1(out))\n out = self.fc2(out)\n return out\n \n\nclass ResBlock(nn.Module):\n def __init__(self, n_chans):\n super(ResBlock, self).__init__()\n self.conv = nn.Conv2d(n_chans, n_chans, kernel_size=1, bias=False)\n self.batch_norm = nn.BatchNorm2d(num_features=n_chans)\n torch.nn.init.kaiming_normal_(self.conv.weight,\n nonlinearity='relu')\n torch.nn.init.constant_(self.batch_norm.weight, 0.5)\n torch.nn.init.zeros_(self.batch_norm.bias)\n\n def forward(self, x):\n out = self.conv(x)\n out = self.batch_norm(out)\n out = torch.relu(out)\n return out + x\n\nclass Net(nn.Module):\n #chans = 32\n #chans less features = 12\n #blocks = 3\n #more blocks 12\n def __init__(self, features=30, n_blocks=5):\n super().__init__()\n self.features = features\n self.conv1 = nn.Conv2d(3, features, kernel_size=1)\n self.conv1_batchnorm = nn.BatchNorm2d(num_features=features)\n self.conv2 = nn.Conv2d(features, features//2, kernel_size=1)\n self.conv2_batchnorm = nn.BatchNorm2d(num_features=features//2)\n self.resblocks = nn.Sequential(\n *(n_blocks * [ResBlock(n_chans=features//2)]))\n self.fc1 = nn.Linear((10) *(10)* (features//2), 32)\n self.fc2 = nn.Linear(32, 2)\n def forward(self, x):\n out = self.conv1_batchnorm(self.conv1(x))\n out = F.max_pool2d(torch.tanh(out),2)\n out = self.conv2_batchnorm(self.conv2(out))\n out = self.resblocks(out)\n out = F.max_pool2d(torch.tanh(out), 2)\n #out1 = F.max_pool2d(out1, 2)\n out = out.view(-1, (10) *(10)* (self.features//2))\n #out1 = out1.view(-1, (10) *(10)* (self.features//2))\n #newout = torch.cat((out),1)\n out = torch.relu(self.fc1(out))\n out = torch.sigmoid(self.fc2(out))\n return out","repo_name":"FelixNahrstedt/Turbine-Analyser","sub_path":"src/utils/model/SatelliteTurbinesDataset.py","file_name":"SatelliteTurbinesDataset.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"4189007357","text":"import datetime as dt\nimport time\nimport calendar\nimport pytz\nfrom datetime import datetime, timedelta\nfrom dateutil import tz\nfrom dateutil.parser import parse\nfrom tzlocal import get_localzone\n\nfrom configurations.config_models.models_choice import *\n\n\nclass UDatetime:\n\n local_tz = get_localzone()\n\n def __init__(self):\n pass\n\n @classmethod\n def now_local(cls):\n return cls.local_tz.localize(datetime.now())\n\n @classmethod\n def localize(cls, date):\n return cls.local_tz.localize(date)\n\n @classmethod\n def to_local(cls, date):\n return date.astimezone(tz=cls.local_tz)\n\n @classmethod\n def datetime_str_init(cls, timestamp,\n default_base=None,\n default_delta=timedelta(days=0),\n empty_default=True\n ):\n if timestamp:\n timestamp = parse(timestamp)\n if not timestamp.tzinfo:\n timestamp = cls.local_tz.localize(timestamp)\n else:\n if empty_default:\n if not default_base:\n default_base = cls.now_local()\n timestamp = default_base + default_delta\n else:\n timestamp = None\n\n return timestamp\n\n @classmethod\n def pick_date_by_one_date(cls, date):\n ahead = date - cls.local_tz.localize(datetime(date.year, date.month, date.day))\n behind = cls.local_tz.localize(datetime(date.year, date.month, date.day) + timedelta(days=1)) - date\n if ahead.total_seconds() >= behind.total_seconds() and behind.total_seconds() <= (3600*6):\n picked_date = (date + timedelta(days=1)).date()\n elif ahead.total_seconds() < behind.total_seconds() and ahead.total_seconds() <= (3600*6):\n picked_date = (date - timedelta(days=1)).date()\n else:\n picked_date = date.date()\n return picked_date\n\n @classmethod\n def pick_date_by_two_date(cls, start, end):\n if start.date() == end.date():\n return start.date()\n elif start.date() + timedelta(days=1) == end.date():\n middle = cls.local_tz.localize(datetime(start.year, start.month, start.day+1))\n ahead = middle - start\n behind = end - middle\n if behind >= ahead:\n return end.date()\n else:\n return start.date()\n else:\n return start.date() + timedelta(days=1)\n\n @classmethod\n def get_overlap(cls, r1_start, r1_end, r2_start, r2_end):\n\n r1_start = r1_start.astimezone(cls.local_tz)\n r1_end = r1_end.astimezone(cls.local_tz)\n r2_start = r2_start.astimezone(cls.local_tz)\n r2_end = r2_end.astimezone(cls.local_tz)\n\n latest_start = max(r1_start, r2_start)\n earliest_end = min(r1_end, r2_end)\n\n delta = earliest_end - latest_start\n\n if delta.total_seconds() > 0:\n return delta\n else:\n return timedelta(hours=0)\n\n @classmethod\n def check_date_format(cls, date_str):\n try:\n datetime.strptime(date_str, '%Y/%m/%d')\n return 'YY/mm/dd'\n except Exception as e:\n pass\n\n try:\n datetime.strptime(date_str, '%m/%d/%Y')\n return 'mm/dd/YY'\n except Exception as e:\n pass\n\n return None\n\n @classmethod\n def date_range(cls, start, end, DOW=None):\n r = (end + timedelta(days=1) - start).days\n date_range = [start + timedelta(days=i) for i in range(r)]\n if DOW:\n date_range_temp = []\n for date in date_range:\n if DOW_choice[date.weekday()][0] in DOW:\n date_range_temp += [date]\n\n date_range = date_range_temp\n\n return date_range\n\n @classmethod\n def week_range(cls, date):\n\n weekday = date.weekday()\n\n start = date - timedelta(days=weekday)\n end = start + timedelta(days=6)\n\n date_range = cls.date_range(start, end)\n\n return date_range\n\n @classmethod\n def date_range_by_DOW(cls, DOW, date=None, week_len=4):\n\n if not date:\n date = UDatetime.now_local().date()\n weekday = date.weekday()\n base = date - timedelta(days=weekday) + timedelta(days=DOW_choice_map[DOW])\n\n date_range = [base + timedelta(days=7*i) for i in range(week_len)]\n\n return date_range\n\n\n\n","repo_name":"chaudryh/djangoRevenueManagementApp","sub_path":"utils/UDatetime.py","file_name":"UDatetime.py","file_ext":"py","file_size_in_byte":4448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"6720488255","text":"import math\nimport numpy as np\nfrom numpy import ma\nimport netCDF4\nfrom netCDF4 import Dataset, num2date\n\nimport halem\nimport halem.Mesh_maker as Mesh_maker\nimport halem.Functions as Functions\nimport halem.Calc_path as Calc_path\nimport halem.Flow_class as Flow_class\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import gridspec as gridspec\nplt.style.use('ggplot')\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\nimport pickle\nfrom scipy.interpolate import griddata\nfrom cartopy import config\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeature\nimport ipywidgets as widgets\nfrom tkinter import *\n\nclass LineBuilder: \n def __init__(self, line):\n self.line = line\n self.xs = []\n self.ys = []\n self.cid = line.figure.canvas.mpl_connect('button_press_event', self)\n self.nodes = []\n\n def __call__(self, event):\n print('click', event)\n if event.inaxes!=self.line.axes: return\n self.xs.append(event.xdata)\n self.ys.append(event.ydata)\n self.line.set_data(self.xs, self.ys)\n self.line.figure.canvas.draw()\n self.nodes.append((event.xdata, event.ydata))\n\nclass mclass:\n def __init__(self, window):\n mainframe = Frame(window)\n mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )\n mainframe.columnconfigure(0, weight = 1)\n mainframe.rowconfigure(0, weight = 1)\n mainframe.pack(pady = 10, padx = 100)\n\n self.tkvar = StringVar(window)\n choices = { '3D_DCSMFM_05_nm','DCSMFM_05_nm', 'DCSMFM_100_m', 'DCSM_zuno_NOOS'}\n self.tkvar.set('DCSMFM_05_nm')\n popupMenu = OptionMenu(mainframe, self.tkvar, *choices)\n Label(mainframe, text=\"Choose a numerical model\").grid(row = 1, column = 1)\n popupMenu.grid(row = 2, column =1)\n\n self.text1 = Text(height=1)\n self.text1.insert(END, 'vship = ')\n self.text1.pack()\n self.vship = Entry()\n self.vship.pack()\n self.text2 = Text(height=1)\n self.text2.insert(END, 't0 = ')\n self.text2.pack()\n self.t0 = Entry()\n self.t0.insert(END, '17/04/2019 01:00:00')\n self.t0.pack()\n\n self.button1 = Button (window, text=\"Select Start & End\", command=self.plot)\n self.button1.pack()\n self.button2 = Button (window, text=\"Calculate Optimal Route\", command=self.calc)\n self.button2.pack()\n \n def plot(self):\n fig = plt.figure(figsize=(5, 5))\n ax = plt.subplot(projection=ccrs.PlateCarree())\n ax.coastlines(resolution='10m', color='black', linewidth=1)\n ax.gridlines(color = 'grey', zorder = 3)\n ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor='palegoldenrod'))\n\n line, = plt.plot([], [], 'b')\n points, = plt.plot([],[], 'ro')\n self.linebuilder = LineBuilder(line)\n self.pointbuilder = LineBuilder(points)\n\n ax.set_extent([4.5, 6, 52.8, 53.8])\n plt.show()\n def calc(self):\n print(self.tkvar.get())\n\n if self.tkvar.get() == '3D_DCSMFM_05_nm':\n name_textfile_load = 'D:/Roadmaps/'\n elif self.tkvar.get() == 'DCSMFM_05_nm':\n name_textfile_load = 'D:/Roadmaps/Rm_DCSM_FM_05nm_WDmin=1.5,nl=(0.9, 1)_idx'\n elif self.tkvar.get() == 'DCSMFM_100_m':\n name_textfile_load = 'D:/Roadmaps/TA_General_waddensea_dt=3h'\n elif self.tkvar.get() =='DCSM_zuno_NOOS':\n name_textfile_load = 'D:/Roadmaps/Roadmap_tidal_anaysis'\n else:\n name_textfile_load = 'D:/Roadmaps/Rm_DCSM_zuno_WDmin=1.5,nl=(1, 1)'\n\n with open(name_textfile_load, 'rb') as input:\n Roadmap = pickle.load(input)\n\n x_r = np.arange(3,7, 0.01)\n y_r = np.arange(52,55, 0.01)\n y_r, x_r = np.meshgrid(y_r,x_r)\n LS_r = griddata((Roadmap.nodes[:,1], Roadmap.nodes[:,0]), Roadmap.WD[:,1], (x_r, y_r), method= 'linear')\n\n t0 = self.t0.get()\n vship = float(self.vship.get())\n\n vvmax = Roadmap.vship[:,-1]\n\n vv= np.abs(vvmax - vship)\n arg_vship = int(np.argwhere(vv == vv.min())[0])\n\n class graph_functions_time:\n function_type = \"time optimalisation\"\n weights = Roadmap.weight_time[arg_vship].weights\n time = Roadmap.weight_time[arg_vship].weights\n vship = Roadmap.vship[arg_vship]\n\n class graph_functions_cost:\n function_type = \"time optimalisation\"\n weights = Roadmap.weight_cost[arg_vship].weights\n time = Roadmap.weight_time[arg_vship].weights\n vship = Roadmap.vship[arg_vship]\n\n class graph_functions_space:\n function_type = \"time optimalisation\"\n weights = Roadmap.weight_space[arg_vship].weights\n time = Roadmap.weight_time[arg_vship].weights\n vship = Roadmap.vship[arg_vship]\n \n start = (np.array(self.linebuilder.nodes)[0,:])[::-1]\n stop = (np.array(self.linebuilder.nodes)[1,:])[::-1]\n\n route_time = Calc_path.Has_route(start, stop, Roadmap, t0, graph_functions_time)\n route_space = Calc_path.Has_route(start, stop, Roadmap, t0, graph_functions_space)\n route_cost = Calc_path.Has_route(start, stop, Roadmap, t0, graph_functions_cost)\n\n fig = plt.figure(figsize=(6, 9))\n gs = gridspec.GridSpec(2, 2)\n ax = plt.subplot(gs[0, 0:2], projection=ccrs.Mercator())\n cval = np.arange(0,30, 0.5)\n plt.contourf(x_r,y_r, LS_r, cval, zorder = 1, transform=ccrs.PlateCarree())\n cbar = plt.colorbar()\n cbar.set_label('Depth [m]')\n plt.plot(route_space.x_route, route_space.y_route, 'y.', transform=ccrs.PlateCarree(), markersize = 5, label = 'Shortest Route')\n plt.plot(route_time.x_route, route_time.y_route, 'm.', transform=ccrs.PlateCarree(), markersize = 5, label = 'Fastest Route')\n plt.plot(route_cost.x_route, route_cost.y_route, 'm.', transform=ccrs.PlateCarree(), markersize = 5, label = 'Fastest Route')\n ax.coastlines(resolution='10m', color='black', linewidth=1)\n ax.gridlines(color = 'grey', zorder = 3)\n ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '10m', edgecolor='face', facecolor='palegoldenrod'))\n t = route_time.route[:,2][-1]\n perc = ((route_space.route[:,1][-1] - route_space.route[:,1][0]) - (route_time.route[:,1][-1] - route_time.route[:,1][0]))/ (route_space.route[:,1][-1] - route_space.route[:,1][0])*100\n #plt.title(\"Fastest route is {} hours and {} minutes, \\n Shorest route is {} km long,\\n Fasest route is {} % faster than the shortest route, \\n Ship speed is {} m/s \\n\"\n # .format(int(t/3600), int((t-int(t/3600)*3600)/60),np.round(route_space.route[:,2][-1]/1000, 2), np.round(perc,2),vship))\n ax.set_extent([4.5, 6, 52.8, 53.8])\n plt.legend(loc = 'best')\n plt.subplot(gs[1, 0])\n halem.plot_timeseries(route_space, Roadmap)\n plt.title('s/t Diagram \\n Shortest Route')\n plt.subplot(gs[1, 1])\n halem.plot_timeseries(route_time, Roadmap)\n plt.title('s/t Diagram \\n Fasest Route')\n plt.show()\n \n\n\nwindow= Tk()\nstart= mclass (window)\nwindow.mainloop()","repo_name":"Pietervanhalem/Personal-Code-Examples","sub_path":"HALEM Notebooks/03_optimize_from_roadmap_GUI.py","file_name":"03_optimize_from_roadmap_GUI.py","file_ext":"py","file_size_in_byte":7259,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"41412409505","text":"import os\nimport csv\n\n#Create empty variables\ntotalvotes = 0\n\ncandidate_list = []\n\n#import csv file \nelection_data = os.path.join('Resources', 'election_data.csv')\n\n#Open a text document\nresults = open('results.txt', 'w')\n\n#open csv file and create variables that will store data as the average P/L is being calculated\nwith open(election_data,'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter = ',')\n header = next(csvreader)\n \n#convert csvreader to a stored list\n candidates = list(csvreader)\n \n#Loop through candidates list to total the number of votes and then to create a list of candidates\n for row in candidates:\n totalvotes = totalvotes + 1\n candidate_list += [row[2]]\n \n#Filter through the candidates list and create a list of each candidate\n charles_list = list(filter(lambda i: 'Charles Casper Stockham' in i, candidate_list))\n diana_list = list(filter(lambda i: 'Diana DeGette' in i, candidate_list))\n raymon_list = list(filter(lambda i: 'Raymon Anthony Doane' in i, candidate_list))\n\n#Find the total number of votes for each candidate based on the length of the list for each candidate\n charles = len(charles_list)\n diana = len(diana_list)\n raymon = len(raymon_list)\n\n#Calculate the the percentage for each candidate\n percent_charles = round((charles/totalvotes)*100, 3)\n percent_diana = round((diana/totalvotes)*100, 3)\n percent_raymon = round((raymon/totalvotes)*100, 3)\n\n#Create dictionary with the results of candidate\n election_results = {'Charles': percent_charles, 'Diana': percent_diana, 'Raymon': percent_raymon}\n\n#Create a new variable that stores the winner of the election by using the election_results dictionary and the max function \n winner = max(election_results, key=election_results.get)\n \n#print all of the results \n print(totalvotes)\n print(percent_charles, charles)\n print(percent_diana, diana)\n print(percent_raymon, raymon)\n print(winner)\n\n#write the report to a text file. \n results.write(f'Election Results\\n-------------\\n')\n results.write(f'Total Votes: {totalvotes}\\n--------------\\n')\n results.write(f'Charles Casper Stockham: {percent_charles}% ({charles})\\n')\n results.write(f'Diana DeGette: {percent_diana}% ({diana})\\n')\n results.write(f'Raymon Anthony Doane: {percent_raymon}% ({raymon})\\n--------------\\n')\n results.write(f'Winner: {winner}\\n-----------------\\n') \n\n \n \n \n \n\n \n \n \n\n \n\n\n \n \n ","repo_name":"mike2463/python-challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"9761143210","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nRealiza a composição dos trabalhos utilizando namespaces\nA pasta de destino eh o ultimo parametro e sera criada caso nao exista\n\nExemplo de uso\n./kcomposer.py questao1.p.cpp questao2.p.cpp questao3.p.cpp pasta_destino\n\nou apenas\n./kcomposer.py *.cpp pasta_destino\n\"\"\"\n__author__ = \"David Sena\"\n\nimport sys\nimport os\nfrom kgenerate import separate\n\n\ndef add_dir_barra(dir_name):\n \"\"\" Se a string dir_name não tiver o / no final\n do nome, então adicione\n \"\"\"\n if dir_name[len(dir_name)-1] != '/':\n dir_name = dir_name + '/'\n return dir_name\n\n\ndef namespace_wrap(question_name, text):\n \"\"\" retorna uma nova string contendo o text\n envolvido por um namespace com nome de\n question_name\n\n \"\"\"\n NID = \"\\nnamespace \" + question_name + \"{\\n\"\n NID_close = \"}\\n\"\n novo = \"\"\n for linha in text.split('\\n'):\n if(len(linha) > 0):\n novo += \" \" + linha + '\\n'\n else:\n novo += \"\\n\"\n return NID + novo + NID_close\n\n\ndef add_only_new(lista, novos):\n \"\"\" Retorna uma nova string com as a lista antiga\n mais as linhas de novos que ainda nao existiam\n na lista\n \"\"\"\n linhas = novos.split('\\n')\n for linha in linhas:\n if lista.find(linha) == -1:\n lista += linha + '\\n'\n return lista\n\n\ndef get_lastname(path):\n indice = 0\n pos = 0\n for letra in path:\n indice += 1\n if(letra == '/'):\n pos = indice\n return path[pos:]\n\n\ndef composer_factory(arquivos, destino):\n testes_main = \"int main(){\\n\"\n includes = \"\"\n aluno = \"\"\n prof = \"\"\n testes = \"\"\n hides = \"\"\n dicas = \"\"\n\n for path in arquivos:\n arq = open(path)\n if(path.find(\".p.cpp\") == -1):\n print(path + \" não tem extensao .p.cpp\")\n continue\n else:\n print(path + \" ok!\")\n\n fname = get_lastname(path).replace(\".p.cpp\", \"\")\n text = arq.read()\n pi = separate(text)\n ID = \"\\n//@question \" + fname + \"\\n\"\n\n namespace_name = \"_\" + fname\n # adiciona a linha de chamada do teste dessa questao\n testes_main += \" \" + namespace_name + \"::tests();\\n\"\n\n # adiciona apenas os include que nao existem\n includes = add_only_new(includes, pi.includes)\n aluno += namespace_wrap(namespace_name, pi.aluno)\n prof += namespace_wrap(namespace_name, pi.prof)\n testes += namespace_wrap(namespace_name, pi.testes.replace('\"fname\"', '\"' + fname + '\"'))\n hides += namespace_wrap(namespace_name, pi.hide.replace('\"fname\"', '\"' + fname + '\"'))\n\n if(len(pi.dicas) > 10):\n dicas += ID + pi.dicas\n\n testes_main += ' cerr << \"#end\" << endl;\\n return 0;\\n}\\n'\n\n # criando pasta e arquivos\n path_destino = destino\n path_destino = add_dir_barra(path_destino)\n aluno_dir = path_destino\n prof_dir = path_destino + \"prof/\"\n if not os.path.exists(path_destino):\n os.makedirs(path_destino)\n if not os.path.exists(prof_dir):\n os.makedirs(prof_dir)\n\n\n # montando estrutura final\n aluno = includes + aluno\n prof = includes + prof\n testes = '#include \"questoes.cpp\"\\n' + testes + dicas + testes_main\n hides = '#include \"questoes.cpp\"\\n' + hides + testes_main\n\n # limpando linhas brancas duplicadas\n aluno = aluno.replace(\"\\n\\n\\n\", \"\\n\\n\")\n testes = testes.replace(\"\\n\\n\\n\", \"\\n\\n\")\n prof = prof.replace(\"\\n\\n\\n\", \"\\n\\n\")\n hides = hides.replace(\"\\n\\n\\n\", \"\\n\\n\")\n\n # abrindo arquivos\n faluno = open(aluno_dir + 'questoes.cpp', 'w')\n ftestes = open(aluno_dir + 'testes.cpp', 'w')\n fprof = open(prof_dir + 'questoes.cpp', 'w')\n fhide = open(prof_dir + 'testes.cpp', 'w')\n\n # escrevendo nos arquivos\n faluno.write(aluno)\n fprof.write(prof)\n ftestes.write(testes)\n fhide.write(hides)\n\n # fechando arquivos\n faluno.close()\n fprof.close()\n ftestes.close()\n fhide.close()\n\n\ndef main():\n tam = len(sys.argv)\n destino = sys.argv[tam - 1]\n arquivos = sys.argv[1:(tam - 1)]\n composer_factory(arquivos, destino)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"senapk/arcade","sub_path":"modelo/scripts/kcomposer.py","file_name":"kcomposer.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"15323982602","text":"from builtins import range \n# ============================================================================= \n__author__ = \"Ostap developers\"\n__all__ = () ## nothing to import\n# ============================================================================= \nimport ROOT, random\nimport ostap.fitting.roofit \nimport ostap.fitting.models as Models\nfrom ostap.fitting.utils import MakeVar \nfrom ostap.core.core import dsID\nfrom ostap.utils.timing import timing \nfrom ostap.logger.utils import rooSilent\n# =============================================================================\n# logging \n# =============================================================================\nfrom ostap.logger.logger import getLogger\nif '__main__' == __name__ or '__builtin__' == __name__ : \n logger = getLogger ( 'test_fitting_simfit4' )\nelse : \n logger = getLogger ( __name__ )\n# =============================================================================\n## make simple test mass \nmass1 = ROOT.RooRealVar ( 'test_mass1' , 'Some test mass' , 0 , 10 )\nmass2 = ROOT.RooRealVar ( 'test_mass2' , 'Some test mass' , 5 , 15 )\n\n## book very simple data set:\nvarset1 = ROOT.RooArgSet ( mass1 )\ndataset1 = ROOT.RooDataSet ( dsID() , 'Test Data set-1' , varset1 ) \n\n## book very simple data set:\nvarset2 = ROOT.RooArgSet ( mass2 )\ndataset2 = ROOT.RooDataSet ( dsID() , 'Test Data set-2' , varset2 ) \n\n## high statistic, low-background \"control channel\"\nmean1 = 5.0\nsigma1 = 0.5\nNS1 = 20000\nNB1 = 2000\n\nfor i in range ( NS1 ) :\n v1 = random.gauss( mean1 , sigma1 )\n if v1 in mass1 :\n mass1.setVal ( v1 )\n dataset1.add ( varset1 )\n\nfor i in range ( NB1 ) :\n v1 = random.uniform ( 0 , 10 )\n if v1 in mass1 :\n mass1.setVal ( v1 )\n dataset1.add ( varset1 )\n \n## low statistic, high-background \"signal channel\"\nNS2 = 500\nNB2 = 10000 \nmean2 = mean1 + 5.0 \nsigma2 = sigma1 * 2.0 \n\nfor i in range(NS2) :\n v2 = random.gauss ( mean2 , sigma2 )\n if v2 in mass2 :\n mass2.setVal ( v2 )\n dataset2.add ( varset2 )\n\nfor i in range (NB2 ) :\n v2 = random.uniform ( 0 , 20 )\n if v2 in mass2 : \n mass2.setVal ( v2 )\n dataset2.add ( varset2 )\n\n# =============================================================================\ndef test_simfit4() :\n \n # =========================================================================\n VARS = MakeVar ()\n \n ## MC/DATA ratio for signal widths\n Rs = ROOT.RooRealVar ( 'Rs' , 'MC/DATA ratio for signal widths' , 1.0 , 0.2 , 3.0 )\n \n ## sigma for normalization peak: sigma from MC multiplied by a factor \n sigma_N = VARS.vars_multiply ( Rs , sigma1 , name = 'sigma_N' )\n \n ## sigma for signal peak: sigma from MC multiplied by the same factor \n sigma_S = VARS.vars_multiply ( Rs , sigma2 , name = 'sigma_S' )\n \n ## Normalization peak:\n signal_N = Models.Gauss_pdf ( 'GN' ,\n xvar = mass1 ,\n mean = ( 3 , 8 ) ,\n sigma = sigma_N )\n \n ## mean of low-statistics signal is constrained to the mean of high statistic signal\n mean_S = VARS.vars_sum ( signal_N.mean , mean2 - mean1 ) \n \n ## low statistic signal :\n signal_S = Models.Gauss_pdf ( 'GS' ,\n xvar = mass2 ,\n mean = mean_S ,\n sigma = sigma_S )\n \n \n # =========================================================================\n ## model for fitting of normalization channel \n model_N = Models.Fit1D ( suffix = 'N' ,\n signal = signal_N ,\n background = -2 ) ## 2nd order positive polynomial \n model_N.S = NS1 \n model_N.B = NB1 \n \n \n ## model for fitting of low-statistic signal channel \n model_S = Models.Fit1D ( suffix = 'S' ,\n signal = signal_S ,\n background = -2 ) ## 2nd order positive polynomial \n \n model_S.S = NS2 \n model_S.B = NB2 \n\n # =========================================================================\n ## make fit for thew normalization channel only \n # =========================================================================\n rN , fN = model_N.fitTo ( dataset1 , draw = None , silent = True )\n rN , fN = model_N.fitTo ( dataset1 , draw = None , silent = True )\n rN , fN = model_N.fitTo ( dataset1 , draw = True , nbins = 50 , silent = True )\n \n logger.info ( 'Fit results for normalization sample only: %s' % rN )\n \n # =========================================================================\n ## make fit for the low-statistic signal channel only \n # =========================================================================\n rS , fS = model_S.fitTo ( dataset2 , draw = None , silent = True )\n rS , fS = model_S.fitTo ( dataset2 , draw = None , silent = True )\n rS , fS = model_S.fitTo ( dataset2 , draw = True , nbins = 50 , silent = True )\n \n logger.info ( 'Fit results for low-statistic signal only: %s' % rS )\n \n # =========================================================================\n ## combine data for simultaneous fit\n # =========================================================================\n \n sample = ROOT.RooCategory ('sample','sample' , 'S' , 'N' )\n \n ## combine datasets\n from ostap.fitting.simfit import combined_data \n vars = ROOT.RooArgSet ( mass1 , mass2 )\n dataset = combined_data ( sample , vars , { 'N' : dataset1 , 'S' : dataset2 } )\n \n ## combine PDFs\n model_sim = Models.SimFit (\n sample , { 'S' : model_S , 'N' : model_N } , name = 'X'\n )\n \n # =========================================================================\n rC , fC = model_sim.fitTo ( dataset , silent = True )\n rC , fC = model_sim.fitTo ( dataset , silent = True )\n rC , fC = model_sim.fitTo ( dataset , silent = True )\n \n fN = model_sim.draw ( 'N' , dataset , nbins = 50 )\n fS = model_sim.draw ( 'S' , dataset , nbins = 50 )\n \n logger.info ( 'Combined fit results are: %s ' % rC )\n \n logger.info ( ' Value | Simple fit | Combined fit ' )\n logger.info ( ' #N | %25s | %-25s ' % ( rS.SS * 1 , rC.SS * 1 ) )\n logger.info ( ' mean | %25s | %-25s ' % ( rS.mean_GN * 1 , rC.mean_GN * 1 ) )\n logger.info ( ' Rs | %25s | %-25s ' % ( rS.Rs * 1 , rC.Rs * 1 ) )\n\n\n# =============================================================================\nif '__main__' == __name__ :\n\n with timing ( \"simfit-5\" , logger ) : \n test_simfit4() \n \n# =============================================================================\n## The END \n# =============================================================================\n","repo_name":"chrisburr/ostap","sub_path":"ostap/fitting/tests/test_fitting_simfit4.py","file_name":"test_fitting_simfit4.py","file_ext":"py","file_size_in_byte":7171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"80"} +{"seq_id":"9906376490","text":"import lightning.pytorch as pl\nimport torch\n\n\ndef set_seed_and_precision(args):\n pl.seed_everything(args.seed, workers=True)\n torch.set_float32_matmul_precision(\"medium\")\n\n\ndef bbox_xyzwhd_to_corners(boxes):\n # Extract individual components from the batched tensor\n x, y, z, w, h, d = torch.split(boxes, 1, dim=-1)\n\n # Calculate the coordinates of the two opposite corners for each box in the batch\n x1 = x - w / 2\n y1 = y - h / 2\n z1 = z - d / 2\n x2 = x + w / 2\n y2 = y + h / 2\n z2 = z + d / 2\n\n # Stack the results into a new tensor of shape (batch_size, 6)\n return torch.cat([x1, y1, z1, x2, y2, z2], dim=-1)\n\n\ndef bbox_centerwhd_to_xyzwhd(boxes):\n cx, cy, cz, w, h, d = torch.split(boxes, 1, dim=-1)\n\n # Calculate top-left coordinates\n x = cx - w / 2\n y = cy - h / 2\n z = cz - d / 2\n\n # Stack the results into a new tensor of shape (batch_size, 6)\n return torch.cat([x, y, x, w, h, d], dim=-1)\n\n\ndef pairwise_iou(boxes1, boxes2):\n boxes1 = bbox_xyzwhd_to_corners(boxes1)\n boxes2 = bbox_xyzwhd_to_corners(boxes2)\n\n # Reshape the input boxes for broadcasting\n boxes1 = boxes1.view(-1, 1, 6) # [M, 1, 6]\n boxes2 = boxes2.view(1, -1, 6) # [1, N, 6]\n\n # Calculate the intersection volume\n min_coords = torch.max(boxes1[..., :3], boxes2[..., :3])\n max_coords = torch.min(boxes1[..., 3:], boxes2[..., 3:])\n intersection_dims = torch.clamp(max_coords - min_coords, min=0)\n intersection_volume = torch.prod(intersection_dims, dim=2) # [M, N]\n\n # Calculate the volume of each box\n volume1 = torch.prod(boxes1[..., 3:] - boxes1[..., :3], dim=2) # [M, 1]\n volume2 = torch.prod(boxes2[..., 3:] - boxes2[..., :3], dim=2) # [1, N]\n\n # Calculate the union volume\n union_volume = volume1 + volume2 - intersection_volume # [M, N]\n\n # Calculate IoU\n return intersection_volume / union_volume\n","repo_name":"elidub/RibFrac","sub_path":"src/misc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"29280692610","text":"# '''\n# The output should be: 30\n# '''\n\nfoo = 20\nfor i in range(10):\n\t\n\t# foo -= 1 This is wrong, need to add 1 every time it loops to reach 30\n\n\tfoo += 1\n\nprint(foo)\n\n","repo_name":"techgrounds/techgrounds-shamimkhaliq71","sub_path":"Python/Code/Bugfix3.py","file_name":"Bugfix3.py","file_ext":"py","file_size_in_byte":168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"44063261938","text":"from random import randint\r\nfrom art import logo\r\n\r\nEASY_LEVEL_TURNS = 10\r\nHARD_LEVEL_TURNS = 5\r\n\r\ndef check_answer(guess, answer, turns):\r\n if guess > answer:\r\n print(\"Меньше\")\r\n return turns - 1\r\n elif guess < answer:\r\n print(\"Больше\")\r\n return turns - 1\r\n else:\r\n print(f\"Ты угадал числом было {answer}.\")\r\n\r\ndef set_difficulty():\r\n level = input(\"Выбери сложность: легкая и сложная: \")\r\n if level == \"легкая\":\r\n return EASY_LEVEL_TURNS\r\n else:\r\n return HARD_LEVEL_TURNS\r\n\r\ndef game():\r\n print(logo)\r\n print(\"Добро пожаловать в игру угадай число\")\r\n print(\"Я загадал случайное число от 1 до 100\")\r\n answer = randint(1, 100)\r\n turns = set_difficulty()\r\n guess = 0\r\n while guess != answer:\r\n print(f\"У тебя есть {turns} попыток угадать число\")\r\n\r\n guess = int(input(\"Предполож�� что это за число: \"))\r\n\r\n turns = check_answer(guess, answer, turns)\r\n if turns == 0:\r\n print(\"Ты проиграл\")\r\n elif guess != answer:\r\n print(\"Попробуй еще раз\")\r\n\r\ngame()\r\n","repo_name":"KyxecGit/GuessingGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"2923860096","text":"from flask import Blueprint, flash, redirect, render_template, request, session\nfrom database.classes import Equipe, Usuario, Partida\n\nwebsite_bp = Blueprint(\n 'website',\n __name__,\n template_folder = 'templates'\n)\n\n\n@website_bp.route('/')\ndef home(): \n return render_template(\n 'home.html',\n equipes=Equipe.listar()\n )\n@website_bp.route('/entrar', methods=['GET', 'POST'])\ndef entrar():\n erros = []\n if request.method == \"POST\":\n form = request.form\n usuario = Usuario.autenticar(\n form.get('usuario'),\n form.get('senha')\n )\n\n if usuario:\n session['usuario'] = usuario.email\n return redirect('/admin')\n else:\n erros.append('E-mail ou senha incorretos!')\n\n return render_template(\n 'entrar.html',\n erros=erros\n )\n\n\n@website_bp.route('/detalhes/')\ndef detalhes(equipe):\n return render_template(\n 'detalhes.html', \n partidas=Partida.listarPorTime(equipe), \n nome=Equipe.obter(equipe).nome)\n\n@website_bp.route('/sair')\ndef sair():\n session.clear()\n return redirect('/')","repo_name":"RenzoYamamoto/ac-4-5-campeonato","sub_path":"website/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16856437847","text":"# load basic packages\n\nimport torch\nfrom torch import nn, optim\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom models import FFWD,SVM,BDT\nimport torch.utils\nimport torch.utils.data\nfrom sklearn import metrics\n\n# Arguments for functions\nimport argparse\nparser = argparse.ArgumentParser(description=\"Preselection & Train/Test Split of Samples\")\nparser.add_argument('--path', help = \"path from where to read files\")\nparser.add_argument('--output', help = \"path where to store files\")\nparser.add_argument('--classifier', help = \"classical ML to be used, options: SVM, DNN, BDT\")\nargs = parser.parse_args()\nif not args.path.endswith('/'):\n path = args.path + \"/\"\nelse:\n path = args.path\nif not args.output.endswith('/'):\n output = args.output + \"/\"\nelse:\n output = args.output\n\n# Load Dataset\nprint('Loading Dataset...')\nX_train = np.load(path+\"X_train.npy\")\ny_train = np.load(path+\"y_train.npy\")\nX_test = np.load(path+\"X_test.npy\")\ny_test = np.load(path+\"y_test.npy\")\nprint('Dataset successfully loaded...')\n\n# Initialization of problem\nif args.classifier == \"DNN\":\n model = FFWD([X_train.shape[1],1024,1024,512,256,128,1])\nelif args.classifier == \"BDT\":\n model = BDT() \nelif args.classifier == \"SVM\":\n model = SVM(nevents=5000)\nprint('Model successfully initialized')\n\n# Training \nmodel.fit(X_train, y_train)\nprint('Model successfully trained')\n\n# Prediction\npred = model.predict(X_test)\nprint('Prediction successfully finished')\n# check if file exists and delete it\nimport os\nif os.path.exists(output+\"pred_\"+args.classifier+\".npy\"):\n os.remove(output+\"pred_\"+args.classifier+\".npy\")\nnp.save(output+\"pred_\"+args.classifier,pred)\n\nfrom sklearn import metrics\nauc = metrics.roc_auc_score(y_test, pred)\nprint(\"AUC store: %f.2\" %auc)\n\n# Calculate accuracy\n#from sklearn.metrics import accuracy_score\n#print(accuracy_score(y_test, pred))\n\n# Calculate AUC with uncertainties\n#from sklearn import metrics\n#auc = []\n\n#X_valid = np.load(path+\"X_valid.npy\")\n#y_valid = np.load(path+\"y_valid.npy\")\n\n#for i in range(X_valid.shape[0]):\n# if args.classifier == \"BDT\":\n# pred = bdt.predict(X_valid[i,:,:])\n# if args.classifier == \"DNN\":\n# # Prediction\n# X_test_device = torch.from_numpy(X_valid[i,:,:]).to(device)\n# with torch.no_grad():\n# pred = ffwd.ffwd(X_test_device.float())\n# pred = pred.cpu().numpy()\n\n# auc.append(metrics.roc_auc_score(y_valid, pred))\n\n#import statistics\n#mean = statistics.mean(auc)\n#stdev = statistics.stdev(auc)\n\n#print(\"AUC store: {0} +/- {1}\".format(mean, stdev))\n","repo_name":"chreissel/QML-project","sub_path":"ClassicalML/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"43966989708","text":"# 자물쇠와 열쇠의 관계를 어떻게 표현할 것인가?\n# 모든 케이스를 조사하는 백트래킹을 사용\nexam_key = [[0, 0, 0], [1, 0, 0], [0, 1, 1]]\nexam_lock = [[1, 1, 1], [1, 1, 0], [1, 0, 1]]\n\n\n# 어떻게 열쇠를 회전시킬 것인가?\n# 회전된 열쇠의 좌표 (i, j) = 기존 열쇠의(n-1-j, i), n은 열쇠의 크기\ndef rotate(key):\n key_len = len(key)\n rotate_key = [[0] * key_len for i in range(key_len)]\n for i in range(key_len):\n for j in range(key_len):\n rotate_key[i][j] = key[key_len-1-j][i]\n return rotate_key\n\n\n# 특정 좌표에서 시작하여 열쇠가 자물쇠에 맞는지 체크합니다.\ndef check_unlock(x, y, key, table):\n answer = True\n m = len(key)\n n = len(table)-(2*(m-1))\n # 테이블의 좌표 m x m 칸을 key 만큼 더해준다.\n # 열쇠와 자물쇠의 돌기가 부딪칠 경우 = 2\n # 열쇠가 자물쇠를 채워주지 못하는 경우 = 0\n for i in range(m):\n for j in range(m):\n table[x+i][y+j] += key[i][j]\n\n # 자물쇠를 푸는 조건에 맞는지 검사합니다.\n # 자물쇠 중 하나라도 1이 아닐 경우 = 0 or 2\n # 0 = 자물쇠의 빈 공간을 채우지 못 했으므로 False\n # 2 = 자물쇠와 열쇠의 돌기가 부딪혔으므로 False\n # 이처럼 두 배열의 조건을 확인할 때, 더하는 것으로 간단하게 표현할 수 있지 않은지 검토해보는 것이 중요하다. (자주 놓치는 부분)\n for i in range(n):\n for j in range(n):\n if table[m-1+i][m-1+j] != 1:\n answer = False\n\n # 더해주었던 열쇠만큼 다시 빼주는 작업입니다.\n for i in range(m):\n for j in range(m):\n table[x+i][y+j] -= key[i][j]\n return answer\n\n\ndef solution(key, lock):\n answer = False\n m = len(key)\n n = len(lock)\n # 열쇠를 하나하나 끼워넣을 테이블 생성 (열쇠는 자물쇠 밖으로 나갈수 있으므로 2*(m-1) + n 크기로 형성)\n solution_table = [[0] * (2*(m-1)+n) for i in range(2*(m-1)+n)]\n for i in range(n):\n for j in range(n):\n solution_table[i+m-1][j+m-1] = lock[i][j]\n\n # 각 좌표를 돌면서 열쇠를 회전시키면서 삽입 후 체크\n for x in range(m-1+n):\n for y in range(m-1+n):\n for i in range(4):\n key = rotate(key)\n if check_unlock(x, y, key, solution_table):\n return True\n return answer\n\n\nprint(solution(exam_key, exam_lock))\n\n","repo_name":"ChanghyunRyu/Python_CodingTest_note","sub_path":"realization/KAKAO_lock_and_key.py","file_name":"KAKAO_lock_and_key.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"8079059488","text":"from django.db import models\nfrom Customer.models import Customer\nfrom cart.models import Cart\nfrom delivery.models import Delivery\n\nclass Order(models.Model):\n order_id = models.AutoField(primary_key=True)\n name = models.CharField(max_length=32)\n order_items = models.TextField()\n total_cost = models.DecimalField(max_digits=8,decimal_places=2)\n delivery_address = models.CharField(max_length=100)\n delivery_date = models.DateField()\n status = models.CharField(max_length=50)\n\n customer = models.ForeignKey(Customer, null= True, on_delete = models.CASCADE)\n cart = models.ForeignKey(Cart, null= True, on_delete = models.CASCADE)\n \n\n \n \n \n \n","repo_name":"EstherMwiyeria/Python-Classwork","sub_path":"order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"36936757913","text":"from GameBoard import GameBoard\nfrom Player import *\n\n\ndef main():\n board = GameBoard()\n\n while True:\n try:\n # input the player one sign\n player1_sign = input(\"Enter player 1 sign: \") # get the input\n # if player enters a null string, will throw a exception\n player1_sign = player1_sign[0] # get the first symbol of player enters a longer string than 1\n break\n except IndexError:\n print(\"It seems that you forgot to enter the sign!\")\n\n while True:\n try:\n # input the player one sign\n player2_sign = input(\"Enter player 2 sign: \") # get the input\n # if player enters a null string, will throw a exception\n player2_sign = player2_sign[0] # get the first symbol of player enters a longer string than 1\n break\n except IndexError:\n print(\"It seems that you forgot to enter the sign!\")\n\n player_versus_computer = input(\"Do you want to play versus computer?(Yes, No) :\")\n\n # if player chose to play vs computer\n # make a human and a computer player\n # and put them in the players list in order to get a turn based gameplay\n if player_versus_computer == \"Yes\" or player_versus_computer == \"yes\":\n human_player = HumanPlayer(player1_sign, board)\n computer_player = ComputerPlayer(player2_sign, board)\n players = (human_player, computer_player)\n else:\n human_player1 = HumanPlayer(player1_sign, board)\n human_player2 = HumanPlayer(player2_sign, board)\n players = (human_player1, human_player2)\n\n # at the beginning of the game, we assume that there is no winner\n winner = False\n\n # print the initial empty board\n board.print_board()\n\n # the restart variable to restart the game\n restart = False\n\n while not winner:\n if restart:\n # we 'restart' the restart :))\n restart = False\n # make another board\n board = GameBoard()\n # assign the new board to the players\n for player in players:\n player.assign_board(board)\n\n # until is no winner we iterate through every player in the 'players' list\n for player in players:\n # current player takes a turn\n # restart will be true if player enters 'restart'\n restart = player.take_turn()\n if restart:\n break\n\n # we show the board after the turn\n board.print_board()\n\n # we check if the player (with his sign) wins the game\n # if the function return true, a winner is found, the while loop will not continue and the game is over\n winner = board.check_for_winner(player.get_player_sign())\n # print the winenr's player symbol\n if winner:\n print()\n print(\"Player %s WON!!!\" % player.get_player_sign())\n break\nmain()","repo_name":"markusokafor/Connect4-App","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"25933347889","text":"from __future__ import print_function\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nfrom keras.layers import Input, Dense, Lambda, Flatten, Reshape\nfrom keras.layers import Conv2D, Conv2DTranspose\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import metrics\nfrom keras.datasets import mnist\nfrom keras.models import load_model\nfrom keras.datasets import cifar10\nfrom keras import optimizers\nfrom utils import *\nfrom keras.callbacks import TensorBoard\nfrom autoencoder import *\nfrom utils import *\nfrom experiments import*\n\n#Laptop version 09/04\n\n#Following the tutorial at https://blog.keras.io/building-autoencoders-in-keras.html & including comments from gregorygunderson.com & jeremyjordan.me\n#Eternal thanks to Beren Millidge for his gestalt_VAE code (https://github.com/Bmillidgework/Generative-Gestalt-Autoencoders/blob/master/gestalt_vae.py) which helped me understand how to include convolutional layers\n\n\ndef vae_model(fname, save=True, save_name = None , verbose = True):\n\n\timgs = load(fname)\n\timgs = np.array(imgs)\n\tx_train, x_test = split_into_test_train(imgs)\n\n\timg_rows, img_cols, img_chns = 100, 100, 3\n\tif K.image_data_format() == 'channels_first':\n\t\t\toriginal_img_size = (img_chns, img_rows, img_cols)\n\telse:\n\t\t\toriginal_img_size = (img_rows, img_cols, img_chns)\n\n\tepochs = 50\n\tbatch_size = 50\n\t# number of convolutional filters to use\n\tfilters = 64\n\t# convolution kernel size\n\tnum_conv = 3\n\n\n\tlatent_dim = 2\n\tintermediate_dim = 128\n\tepsilon_std = 1.0\n\tactivation = 'relu'\n\t# input image dimensions\n\tinput_shape = (100, 100, 3) #Define shape without including the batch size\n\n\t#First we create the encoder network which maps inputs to our latent distribution parameters:\n\tx = Input(shape=input_shape)\n\tconv_1 = Conv2D(img_chns,\n\t\t\t\t\tkernel_size=(2, 2),\n\t\t\t\t\tpadding='same', activation=activation)(x) #Inputs & outputs a 4D tensor\n\tif verbose:\n\t\tprint (conv_1.shape)\n\tconv_2 = Conv2D(filters,\n\t\t\t\t\tkernel_size=(2, 2),\n\t\t\t\t\tpadding='same', activation=activation,\n\t\t\t\t\tstrides=(2, 2))(conv_1)\n\tif verbose:\n\t\tprint (conv_2.shape)\n\tconv_3 = Conv2D(filters,\n\t\t\t\t\tkernel_size=num_conv,\n\t\t\t\t\tpadding='same', activation=activation,\n\t\t\t\t\tstrides=1)(conv_2)\n\tif verbose:\n\t\tprint (conv_3.shape)\n\tconv_4 = Conv2D(filters,\n\t\t\t\t\tkernel_size=num_conv,\n\t\t\t\t\tpadding='same', activation=activation,\n\t\t\t\t\tstrides=2)(conv_3)\n\tif verbose:\n\t\tprint (conv_4.shape)\n\tflat = Flatten()(conv_4) #For generating the latent vector\n\tif verbose:\n\t\tprint (flat.shape)\n\thidden = Dense(intermediate_dim, activation=activation)(flat)\n\tif verbose:\n\t\tprint (hidden.shape)\n\n\tz_mean = Dense(latent_dim)(hidden)\n\tz_log_sigma = Dense(latent_dim)(hidden) #Use log variance instead of standard deviation as it is more convenient and helps with numerical stability\n\n\t#Use the latent distribution parameters to sample new & similar points from the latent space\n\tdef sampling(args):\n\t\tz_mean, z_log_sigma = args\n\t\tepsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim),\n\t\t\t\t\t\t\t\t mean=0., stddev=epsilon_std) #Normally distributed values in a tensor to be used as noise\n\t\treturn z_mean + K.exp(z_log_sigma) * epsilon\n\t#Shifting the random sample by the mean and scaling it by the variance\n\n\t#Make the sampling the input\n\tz = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_sigma]) #Function, output shape multiplied by args\n\t#Lambda wraps an arbitrary expression as a layer, so here we are wrapping the sampling (latent space) as our input layer\n\n\t#Map the latent points to reconstructed inputs\n\tdecoder_hid = Dense(intermediate_dim, activation=activation)\n\n\tdecoder_upsample = Dense(filters * int(img_rows/4) * int(img_cols/4), activation=activation)\n\n\tif K.image_data_format() == 'channels_first':\n\t\toutput_shape = (batch_size, filters, int(img_rows/4), int(img_cols/4))\n\telse:\n\t\toutput_shape = (batch_size, int(img_rows/4), int(img_cols/4), filters)\n\n\tdecoder_reshape = Reshape(output_shape[1:]) #Reshapes the output\n\tdecoder_deconv_1 = Conv2DTranspose(filters,\n\t\t\t\t\t\t\t\t\t kernel_size=num_conv,\n\t\t\t\t\t\t\t\t\t padding='same',\n\t\t\t\t\t\t\t\t\t strides=1,\n\t\t\t\t\t\t\t\t\t activation=activation) #Transposed layers for deconvolution\n\tdecoder_deconv_2 = Conv2DTranspose(filters,\n\t\t\t\t\t\t\t\t\t kernel_size=num_conv,\n\t\t\t\t\t\t\t\t\t padding='same',\n\t\t\t\t\t\t\t\t\t strides=2,\n\t\t\t\t\t\t\t\t\t activation=activation)\n\tif K.image_data_format() == 'channels_first':\n\t\toutput_shape = (batch_size, filters, int(img_rows+1), int(img_cols+1))\n\telse:\n\t\toutput_shape = (batch_size, int(img_rows+1), int(img_cols+1), filters)\n\tdecoder_deconv_3_upsamp = Conv2DTranspose(filters,\n\t\t\t\t\t\t\t\t\t\t\t kernel_size=(3, 3),\n\t\t\t\t\t\t\t\t\t\t\t strides=(2, 2),\n\t\t\t\t\t\t\t\t\t\t\t padding='valid',\n\t\t\t\t\t\t\t\t\t\t\t activation=activation)\n\tdecoder_mean_squash = Conv2D(img_chns,\n\t\t\t\t\t\t\t\t kernel_size=2,\n\t\t\t\t\t\t\t\t padding='valid',\n\t\t\t\t\t\t\t\t activation='sigmoid')\n\n\thid_decoded = decoder_hid(z)\n\tup_decoded = decoder_upsample(hid_decoded)\n\treshape_decoded = decoder_reshape(up_decoded)\n\tdeconv_1_decoded = decoder_deconv_1(reshape_decoded)\n\tdeconv_2_decoded = decoder_deconv_2(deconv_1_decoded)\n\tx_decoded_relu = decoder_deconv_3_upsamp(deconv_2_decoded)\n\tx_decoded_mean_squash = decoder_mean_squash(x_decoded_relu)\n\n\n\t#Instantiate 3 models\n\n\t#End-to-end autoencoder for mapping inputs to reconstructions\n\tvae = Model(x, x_decoded_mean_squash)\n\n\tkl = kl_loss(z_mean, z_log_sigma)\n\tvae.add_loss(kl)\n\n\t#Encoder mapping from inputs to latent space\n\tencoder = Model(x, z_mean)\n\n\t#Generator which takes points from the latent space to output the reconstructed samples\n\tdecoder_input = Input(shape=(latent_dim,))\n\t_hid_decoded = decoder_hid(decoder_input)\n\t_up_decoded = decoder_upsample(_hid_decoded)\n\t_reshape_decoded = decoder_reshape(_up_decoded)\n\t_deconv_1_decoded = decoder_deconv_1(_reshape_decoded)\n\t_deconv_2_decoded = decoder_deconv_2(_deconv_1_decoded)\n\t_x_decoded_relu = decoder_deconv_3_upsamp(_deconv_2_decoded)\n\t_x_decoded_mean_squash = decoder_mean_squash(_x_decoded_relu)\n\t#Push z through decoder\n\tgenerator = Model(decoder_input, _x_decoded_mean_squash)\n\n\n\t#Time to train!\n\n\tx_train = x_train.astype('float32') / 255.\n\tx_test = x_test.astype('float32') / 255.\n\tprint (x_test.shape)\n\n\tshape = x_train.shape[1:]\n\n\t#Train using the end-to-end model with a custom loss & K-L divergence regularization\n\t\"\"\"def vae_loss(x, x_decoded_mean):\n\t\txent_loss = metrics.binary_crossentropy(x, x_decoded_mean_squash) #Reconstruction loss\n\t\t#Binary crossentropy because the decoding term is a Bernoulli multi layered perceptron - is it worth also trying Gaussian + MSE??\n\t\tkl_loss = - 0.5 * K.mean(1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma), axis=-1) #Variational loss\n\t\treturn xent_loss + kl_loss #Combine the losses\n\t\"\"\"\n\t#Can only get these losses to work when we define them outside of the VAE model\n\tvae.compile(optimizer='adam',loss= reconstruction_loss)\n\tvae.summary()\n\n\tvae.fit(x_train, x_train,\n\t\t\tshuffle=True,\n\t\t\tepochs=epochs,\n\t\t\tbatch_size=batch_size,\n\t\t\tvalidation_data= (x_test, x_test))\n\n\tpredictions = vae.predict(x_test, batch_size=batch_size)\n\n\tif save:\n\t\tsave_array((x_test, predictions), save_name + '_imgs_preds')\n\n#Need to define losses here because it wasn't working trying to define them in the vae_model definition\ndef reconstruction_loss(y, x_decoded):\n\t#let's hard code this for now\n\trows = 8\n\tcols = 32\n\trec_loss = rows * cols * metrics.binary_crossentropy(K.flatten(y), K.flatten(x_decoded))\n\tprint(\"Rec loss: \" + str(rec_loss))\n\treturn rec_loss\n\ndef kl_loss(z_mean, z_log_sigma):\n\tklloss = -0.5 * K.sum(1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma), axis=-1)\n\t#print(\"KL loss: \" + str(klloss))\n\treturn klloss\n\ndef main():\n\n\tif len(sys.argv) >=2:\n\t\tfname = sys.argv[1]\n\n\tsave_name = 'variational_50_epochs'\n\n\tvae_model(fname, save = True, save_name = save_name)\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"AmyGee/Visual-Processing","sub_path":"VAE_conv.py","file_name":"VAE_conv.py","file_ext":"py","file_size_in_byte":7827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"614936076","text":"from django.shortcuts import render\nfrom .models import Course, TeachRequest, Post, MsgRequest\nfrom .forms import JoinAsLect, SendMsg\nfrom django.core.paginator import Paginator\nfrom django.contrib import messages\n# Create your views here.\n\ndef index(request):\n courses = Course.objects.all().order_by('cid').values().reverse()\n context = {\n \"courses\": courses\n }\n return render(request, \"all_courses.html\", context)\n\n\n\n\ndef cdetails(request):\n\n cid = request.GET['cid']\n newprice = \"ERR\"\n course = Course.objects.get(cid=cid)\n discountok = course.discount > 0\n if discountok:\n newprice = course.price - (course.discount/100) * course.price\n\n context = {\n \"course\":course,\n \"newprice\":newprice,\n \"discountok\":discountok,\n }\n #context['type'] = course[0]\n return render(request, \"course_details.html\", context)\n\ndef join_as_lect(request):\n form = JoinAsLect()\n if request.method == \"POST\":\n print(request.POST['name'])\n form = JoinAsLect(request.POST)\n if form.is_valid():\n \n pc = TeachRequest(\n name = request.POST['name'],\n phone = request.POST['phone'],\n description = request.POST['description']\n )\n \n pc.save()\n messages.success(request, 'شكرا, تم تسجيل معلوماتك')\n else:\n messages.error(request, 'عذرا, يوجد خطأ في بياناتك!')\n return render(request, \"join_as_lect.html\")\n context = {\n \n }\n return render(request, \"join_as_lect.html\", context)\n\n\n\ndef latest_news(request):\n queryset = Post.objects.all().order_by('-created_at')\n\n paginator = Paginator(queryset, 5) # Show 5 posts per page\n\n page_number = request.GET.get('page') # Get the current page number from the request parameters\n page_obj = paginator.get_page(page_number) # Get the corresponding page object\n\n context = {'page_obj': page_obj}\n return render(request, 'latest_news.html', context)\n\n\ndef news_post(request):\n pid = request.GET['pid']\n print(pid)\n post = Post.objects.get(id=pid)\n\n context = {\n 'post':post\n }\n return render(request, 'news_post.html', context)\n\n\ndef custom_page_not_found(request, exception):\n return render(request, '404.html', status=404)\n\ndef contact(request):\n form = SendMsg()\n if request.method == \"POST\":\n form = SendMsg(request.POST)\n print(request.POST['name'], request.POST['phone'], request.POST['msg'])\n print(form.errors)\n if form.is_valid():\n \n pc = MsgRequest(\n name = request.POST['name'],\n phone = request.POST['phone'],\n msg = request.POST['msg']\n )\n \n pc.save()\n messages.success(request, 'شكرا, تم تسجيل معلوماتك')\n else:\n messages.error(request, 'عذرا, يوجد خطأ في بياناتك!')\n return render(request, \"contact.html\")\n return render(request, 'contact.html')","repo_name":"devmohamd47/courses","sub_path":"available_courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"70465657540","text":"class Solution:\n def reorderLogFiles(self, logs):\n text = []\n dig = []\n res = []\n for i in logs:\n l = []\n items = i.split(\" \")\n if items[1].isdigit():\n dig.append(\" \".join(items))\n else:\n text.append((items[0], ' '.join(items[1:])))\n\n text.sort(key=lambda x:(x[1], x[0]))\n\n res = [' '.join(tups) for tups in text]\n res.extend(dig)\n return res\n\nif __name__ == \"__main__\":\n solution = Solution()\n logs = [\"dig1 8 1 5 1\", \"let1 art can\", \"dig2 3 6\", \"let2 own kit dig\", \"let3 art zero\"]\n res1 = solution.reorderLogFiles(logs)\n print(res1)\n","repo_name":"DarkAlexWang/leetcode","sub_path":"Amazon/OnlineAssessment/reorder_log_files.py","file_name":"reorder_log_files.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"2390683273","text":"from ex115.lib.interface import *\n\n\ndef cadastrar_pessoa():\n nome = str(input('Nome: ')).strip()\n idade = leia_int('Idade: ')\n try:\n with open('dados.txt', 'a') as arquivo:\n arquivo.write(str(nome) + '\\n')\n arquivo.write(str(idade) + '\\n')\n print('Dados salvos com sucesso!')\n except Exception as erro:\n print('ERRO! Não foi possível salvar as informações.')\n print(erro)\n\n\ndef ver_pessoas_cadastradas():\n with open('dados.txt', 'r') as arquivo:\n pessoas = arquivo.readlines()\n for index in range(0, len(pessoas), 2):\n nome = str(pessoas[index].rstrip('\\n'))\n idade = str(pessoas[index + 1]).rstrip('\\n')\n print(f'{nome:34}{idade:>3} anos')\n linha()","repo_name":"rodrigolnaves/Teste","sub_path":"ex115/lib/arquivo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"1705688217","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\nimport json\n\ncred=credentials.Certificate('key.json')\n\nfirebase_admin.initialize_app(cred,{\n 'databaseURL' : 'https://capstone-116d0-default-rtdb.firebaseio.com/'\n})\nref = db.reference('soundData')\ndata=ref.get()\n# JSON 문자열로 변환\njson_string = json.dumps(data)\n\n# JSON 문자열 파싱\nparsed_data = json.loads(json_string)\n\n# 두 번째 값들 추출\nvalues = list(parsed_data.values())\nsecond_values = [int(value) for value in values]\n\nprint(second_values)","repo_name":"hyunjin-h/FloorNoise","sub_path":"firebase_test2.py","file_name":"firebase_test2.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"17134016255","text":"def remove_duplicates(a_list):\n new_list = []\n for i in a_list:\n if i in new_list:\n continue\n else:\n new_list.append(i)\n return new_list\n\nlist1 = ['a','a','b','c','c','d','e']\nnew_list1 = remove_duplicates(list1)\nprint(new_list1)\n\n\ndef remove_duplicates_easier(a_list):\n new_list = []\n for i in a_list:\n if i not in new_list:\n new_list.append(i)\n return new_list\nprint(new_list1)\n\ndef square(x):\n if x < 0 or x > 10:\n return 'Error'\n elif type(x) != int:\n return 'Error'\n else:\n return x * x\n","repo_name":"FelixHilker/hackademy-day5","sub_path":"production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"27166174978","text":"from itertools import permutations\n\n\n# 소수 판별 함수\ndef prime_num(n):\n if n < 2:\n return False\n for i in range(2, n):\n if n % i == 0:\n return False\n return True\n\n\ndef solution(numbers):\n answer = 0\n listchar = []\n result1 = []\n # 순열이 담긴 리스트 만들기\n for i in range(1, len(numbers) + 1):\n tmp = list(permutations(numbers, i))\n # [[\"0\"],[\"1\"],[\"1\"]],[[\"0\",\"1\"],[\"0\",\"1\"],[\"1\",\"1\"]],[[\"0\",\"1\",\"1\"]]\n listchar += [int(''.join(i)) for i in tmp] # 원소 하나로 합치기\n result1 = list(set(listchar)) # set 활용해서 중복제거 [0,1,11]\n\n # 리스트 카운트 (체)\n for i in result1:\n if prime_num(i):\n answer += 1\n else:\n continue\n\n return answer","repo_name":"dohyunre702/Algorithm_java","sub_path":"프로그래머스/소수찾기.py","file_name":"소수찾기.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"29986438231","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 21 20:55:08 2021\r\n\r\n@author: user\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\n\r\ndef perceptron_no_offset(x,y,epochs):\r\n '''\r\n x is a feature matrix\r\n y is a label vector\r\n Both need to be numpy arrays\r\n '''\r\n #Initialize array theta=0\r\n theta = np.zeros(x.shape[1])\r\n \r\n for t in range(epochs):\r\n for i in range(x.shape[0]):\r\n #For every feature row vector in the feature matrix\r\n if y[i] * np.dot(x[i], theta) <= 0:\r\n '''\r\n If y does not match the prediction of the linear classifier \r\n (product < 0) or the prediction is uncertain (product is 0), \r\n update the parameters of the theta vector.\r\n '''\r\n #Nudges the theta parameters in the same/opposite direction\r\n #(determined by y) of the feature row vector. \r\n theta += y[i]*x[i] \r\n return theta\r\n","repo_name":"marcio-pg/MITx-6.86x---Machine-Learning-with-Python-From-Linear-Models-to-Deep-Learning","sub_path":"Perceptron (No offset).py","file_name":"Perceptron (No offset).py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"71643511618","text":"from numpy import array\nfrom os import path, listdir\nfrom cv2 import IMREAD_GRAYSCALE, resize, imread\nfrom tqdm import tqdm\nfrom random import shuffle\nfrom tensorflow import keras\n\n\nDATADIR = [\"GC_SI\"]\nCATEGORIES = [\"DOWN\", \"UP\"]\ntraining_data = []\nIMG_SIZE = 256\n\n\ndef main():\n X = []\n y = []\n create_training_data()\n shuffle(training_data)\n for features, label in training_data:\n X.append(features)\n y.append(label)\n X = array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\n train_images = array(X[100:] / 255.0)\n test_images = array(X[:100] / 255.0)\n train_labels = array(y[100:])\n test_labels = array(y[:100])\n model = keras.Sequential([keras.layers.Flatten(input_shape=(\n IMG_SIZE, IMG_SIZE)), keras.layers.Dense(1024, activation='relu'), keras.layers.Dense(2)])\n model.compile(optimizer='adam', loss=keras.losses.SparseCategoricalCrossentropy(\n from_logits=True), metrics=['accuracy'])\n model.fit(train_images, train_labels, epochs=2)\n test_loss, test_acc = model.evaluate(test_images, test_labels)\n print(\"\\ntesting data provided loss: \" +\n str(test_loss) + \" and accuracy: \" + str(test_acc))\n\n\ndef create_training_data():\n for datadir in DATADIR:\n for category in CATEGORIES:\n newPath = path.join(datadir, category)\n class_num = CATEGORIES.index(category)\n for img in tqdm(listdir(newPath)):\n try:\n img_array = imread(path.join(\n path, img), IMREAD_GRAYSCALE)\n new_array = resize(img_array, (IMG_SIZE, IMG_SIZE))\n training_data.append([new_array, class_num])\n except Exception as e:\n print(str(e))\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"hedge0/PyFinance-Projects","sub_path":"MLgraphs/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"80"} +{"seq_id":"23469375133","text":"#program shines LED then shuts down 90 seconds later\n#By Jeremy S. Cook 4/20/2020\n\nimport os\nimport time\nimport RPi.GPIO as GPIO\n\nLED1 = 14\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(LED1, GPIO.OUT)\nprint (\"I'm baaaaack!\")\nprint (\"LED on, will shut down in 90 seconds\")\nGPIO.output(LED1, GPIO.HIGH)\ntime.sleep(90)\nprint (\"Goodbye for now!\")\nos.system(\"sudo shutdown -h now\")\nGPIO.output(LED1, GPIO.LOW)\nGPIO.cleanup\nquit()\n","repo_name":"JeremySCook/Intermittent-Shutdown","sub_path":"blink-off.py","file_name":"blink-off.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"80"} +{"seq_id":"8962151519","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[58]:\n\n\nimport pandas as pd\nimport requests\nfrom pandas.io.json import json_normalize\n\n\n# Get the schedule Data for Vancouver\n\n# In[59]:\n\n\nurl = 'http://data.streetfoodapp.com/1.1/schedule/vancouver'\n\ndata = requests.get(url).json()\ndfVan = pd.DataFrame.from_dict(data)\ndfVan.head()\n\n\n# In[60]:\n\n\nurl = 'http://data.streetfoodapp.com/1.1/schedule/vancouver'\ndata = requests.get(url).json()\ndata = df.vendors.apply(pd.Series)\ndata.head()\n\n\n# In[61]:\n\n\ndata2 = data[['description', 'name', 'description_short', 'last']].copy()\ndata2 = data2.dropna()\ndata2.head()\n\n\n# In[64]:\n\n\nVandata = data2[\"last\"].apply(pd.Series)\nVandata.insert(4, \"Location\", \"Vancouver\")\nVandata.head()\n\n\n# Grab Boston\n\n# In[66]:\n\n\nurl = 'http://data.streetfoodapp.com/1.1/schedule/boston'\ndata = requests.get(url).json()\ndata = df.vendors.apply(pd.Series)\ndata.head()\n\n\n# In[67]:\n\n\ndata2 = data[['description', 'name', 'description_short', 'last']].copy()\ndata2 = data2.dropna()\ndata2.head()\n\n\n# In[68]:\n\n\nBosdata = data2[\"last\"].apply(pd.Series)\nBosdata.insert(4, \"Location\", \"Boston\")\nBosdata.head()\n\n\n# Get the Tallahassee Data\n\n# In[69]:\n\n\nurl = 'http://data.streetfoodapp.com/1.1/schedule/tallahassee'\ndata = requests.get(url).json()\ndata = df.vendors.apply(pd.Series)\ndata.head()\n\n\n# In[70]:\n\n\ndata2 = data[['description', 'name', 'description_short', 'last']].copy()\ndata2 = data2.dropna()\ndata2.head()\n\n\n# In[71]:\n\n\nTalladata = data2[\"last\"].apply(pd.Series)\nTalladata.insert(4, \"Location\", \"Tallahassee\")\nTalladata.head()\n\n\n# In[72]:\n\n\nmerged_df = pd.concat([Bosdata,Talladata, Vandata])\nmerged_df.head()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"jillpeloquin13/group_project_FoodTruck","sub_path":"WorkingNB/FoodTruckETLv2 (1).py","file_name":"FoodTruckETLv2 (1).py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"2172376141","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass LeNet(nn.Module):\n \"\"\" A LeNet model, supporting parameters described in the paper by Du et al.\"\"\"\n \n def __init__(self, n_classes, in_channels=1, input_size=28, paper_params=False):\n super(LeNet, self).__init__()\n \n if input_size not in [28, 32]:\n raise ValueError(\"Linear layers are not defined for input image sizes other than 28 or 32.\")\n \n if paper_params: # Use parameters described in the paper\n self.feature_extractor = nn.Sequential(\n nn.Conv2d(in_channels=in_channels, out_channels=32, kernel_size=2, stride=1),\n nn.Tanh(),\n nn.AvgPool2d(kernel_size=2),\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=2, stride=1),\n nn.Tanh(),\n nn.AvgPool2d(kernel_size=2),\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=2, stride=1),\n nn.Tanh()\n )\n \n self.classifier = nn.Sequential(\n nn.Linear(in_features=(4608 if input_size == 32 else 3200), out_features=800),\n nn.Tanh(),\n nn.Linear(in_features=800, out_features=n_classes),\n )\n else: # Use parameters giving better results on the MNIST dataset\n self.feature_extractor = nn.Sequential(\n nn.Conv2d(in_channels=in_channels, out_channels=6, kernel_size=5, stride=1),\n nn.Tanh(),\n nn.AvgPool2d(kernel_size=2),\n nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5, stride=1),\n nn.Tanh(),\n nn.AvgPool2d(kernel_size=2),\n nn.Conv2d(in_channels=16, out_channels=120, kernel_size=4, stride=1),\n nn.Tanh()\n )\n \n self.classifier = nn.Sequential(\n nn.Linear(in_features=(480 if input_size == 32 else 120), out_features=84),\n nn.Tanh(),\n nn.Linear(in_features=84, out_features=n_classes),\n )\n \n def forward(self, x):\n x = self.feature_extractor(x)\n x = torch.flatten(x, 1)\n logits = self.classifier(x)\n probs = F.softmax(logits, dim=1)\n return logits, probs\n","repo_name":"CENG501-Projects/CENG501-Spring2022","sub_path":"Project_Kuzucu_Tezoren/lib/cnn/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"80"} +{"seq_id":"72793202818","text":"\"\"\"\nSelect sample of MaNGA galaxies.\n\"\"\"\n\nfrom __future__ import division, print_function, absolute_import\nimport os\nimport copy\nfrom collections import defaultdict\n\nimport numpy as np\nfrom astropy.io import fits\n\n\n# See Marvin docs for details on how to download MaNGA galaxies\n# http://sdss-marvin.readthedocs.io/en/latest/core/downloads.html\n\ndef set_drpver(drpver=None, release=None):\n \n from marvin import config\n \n assert not ((drpver is not None) and (release is not None)), \\\n ('Both ``drpver`` and ``release`` are set (drpver: {0}, release: {1}). '\n 'Only set one of them.'.format(drpver, release))\n\n drpver_ = drpver\n if drpver is not None:\n release = config.lookUpRelease(drpver)\n \n if release is not None:\n config.setRelease(release)\n \n drpver, __ = config.lookUpVersions()\n \n if drpver_ is not None:\n assert drpver == drpver_, 'DRP versions do not match.'\n \n return drpver\n\n\ndef read_drpall(drpver=None, release=None, path_drpall=None):\n drpver = set_drpver(drpver, release)\n\n if path_drpall is None:\n path_drpall = os.path.join(os.environ['MANGA_SPECTRO_REDUX'], drpver)\n\n drpall_file = os.path.join(path_drpall, 'drpall-{}.fits'.format(drpver))\n data = fits.getdata(drpall_file, 1)\n return data\n\n\ndef apply_bitmasks(data, bits):\n subsamples = [data & 2**bit for bit in bits]\n return np.logical_or.reduce(subsamples)\n\n\ndef remove_duplicates(plateifus, mangaids, sn2):\n # keys are unique mangaids and values are indices within ``mangaids`` array\n mangaid_lookup = defaultdict(list)\n for ii, item in enumerate(mangaids):\n mangaid_lookup[item].append(ii)\n\n # keys are duplicate mangaids and values are indices within ``mangaids``\n duplicates = {k: v for k, v in mangaid_lookup.items() if len(v) > 1}\n\n uniques = copy.deepcopy(mangaid_lookup)\n for kk, vv in duplicates.items():\n # Choose plateifu with highest SN2 (sum of blueSN2 and redSN2)\n uniques[kk] = [vv[np.argmax(sn2[vv])]]\n\n inds = np.array([it for val in uniques.values() for it in val])\n return plateifus[inds]\n\n\ndef write(plateifus, filepath, header=None):\n with open(filepath, 'w') as fout:\n if header is not None:\n fout.write(header)\n\n for plateifu in plateifus:\n fout.write('{0}\\n'.format(plateifu))\n","repo_name":"bretthandrews/mglearn","sub_path":"mglearn/selection.py","file_name":"selection.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"275904620","text":"import numpy as np\n\nimport pytest\n\nfrom .. import tree_layout as tl\nfrom ..tree import NewickTree\n\n\ndef test_invalid_input():\n with pytest.raises(TypeError) as exc:\n layout = tl.TreeLayout(None)\n assert exc.value.args[0] == 'Input not a tree object: %s' % type(None)\n\n\ndef test_layout_indexable_by_tree_or_id():\n tree = NewickTree('((0,1)4,(2,3)5)6;')\n layout = tl.TreeLayout(tree)\n assert layout[tree] is layout[tree.id]\n\n\ndef test_default_layout():\n tree = NewickTree('((0,1)4,(2,3)5)6;')\n layout = tl.TreeLayout(tree)\n\n t6 = tree\n t4, t5 = t6.children\n t0, t1 = t4.children\n t2, t3 = t5.children\n\n ts = [t0, t1, t2, t3, t4, t5, t6]\n xs = [-1.5, -.5, .5, 1.5, -1, 1, 0]\n ys = [2, 2, 2, 2, 1, 1, 0]\n\n for t, x, y in zip(ts, xs, ys):\n assert layout[t].x == x\n assert layout[t].y == y\n assert layout[t].width == 1\n assert layout[t].height == 0\n\n\ndef test_layout_single_leaf():\n tree = NewickTree('0;')\n layout = tl.TreeLayout(tree)\n assert layout[tree].x == 0\n assert layout[tree].y == 0\n\n\ndef test_pick():\n\n tree = NewickTree('((0,1)4,(2,3)5)6;')\n layout = tl.TreeLayout(tree)\n\n #exact match\n assert layout.pick(0, 0) is tree\n\n #closest match, below\n assert layout.pick(0, -1) is tree\n\n #only pick if y position is <= node\n assert layout.pick(-.01, .01) is tree.children[0]\n assert layout.pick(0, 2.1) is None\n\n\ndef test_tree_to_xy():\n tree = NewickTree('(0,1)2;')\n layout = tl.TreeLayout(tree)\n\n x = np.array([0, 0, -.5, -.5, None, 0, .5, .5, None], dtype=float)\n y = np.array([0, 0, 0, 1, None, 0, 0, 1, None], dtype=float)\n\n xx, yy = layout.tree_to_xy(tree)\n\n np.testing.assert_array_almost_equal(x, np.array(xx, dtype=float))\n np.testing.assert_array_almost_equal(y, np.array(yy, dtype=float))\n\n\ndef test_tree_to_xy_list():\n tree = NewickTree('(0,1)2;')\n layout = tl.TreeLayout(tree)\n\n x = np.array([-0.5, None, .5, None], dtype=float)\n y = np.array([1, None, 1, None], dtype=float)\n\n xx, yy = layout.tree_to_xy(tree.children)\n\n np.testing.assert_array_almost_equal(x, np.array(xx, dtype=float))\n np.testing.assert_array_almost_equal(y, np.array(yy, dtype=float))\n\n\ndef test_branch_to_xy_branch():\n tree = NewickTree('((0,1)4,(2,3)5)6;')\n layout = tl.TreeLayout(tree)\n\n x = [-1, -1, 0]\n y = [1, 0, 0]\n\n xx, yy = layout.branch_to_xy(tree.children[0])\n\n np.testing.assert_array_almost_equal(x, xx)\n np.testing.assert_array_almost_equal(y, yy)\n\n\ndef test_branch_to_xy_root():\n tree = NewickTree('((0,1)4,(2,3)5)6;')\n layout = tl.TreeLayout(tree)\n\n x = [0]\n y = [0]\n xx, yy = layout.branch_to_xy(tree)\n np.testing.assert_array_almost_equal(x, xx)\n np.testing.assert_array_almost_equal(y, yy)\n\n\ndef test_branch_to_xy_leaf():\n tree = NewickTree('((0,1)4,(2,3)5)6;')\n layout = tl.TreeLayout(tree)\n\n x = [-1.5, -1.5, -1]\n y = [2, 1, 1]\n xx, yy = layout.branch_to_xy(tree.children[0].children[0])\n np.testing.assert_array_almost_equal(x, xx)\n np.testing.assert_array_almost_equal(y, yy)\n\n\ndef test_branch_to_xy_list():\n tree = NewickTree('((0,1)4,(2,3)5)6;')\n layout = tl.TreeLayout(tree)\n x = np.array([0, None, 0, None], dtype=float)\n y = np.array([0, None, 0, None], dtype=float)\n\n xx, yy = layout.branch_to_xy([tree, tree])\n np.testing.assert_array_almost_equal(x, np.array(xx, dtype=float))\n np.testing.assert_array_almost_equal(y, np.array(yy, dtype=float))\n","repo_name":"glue-viz/glue-qt-old","sub_path":"glue/core/tests/test_tree_layout.py","file_name":"test_tree_layout.py","file_ext":"py","file_size_in_byte":3504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"24617370387","text":"## This file loads model locally\n\nimport pandas as pd\nimport os\nimport lightgbm as lgb\nfrom flask import Flask, request, jsonify\n\nmodel = lgb.Booster(model_file='model.lgb')\n\ndef preprocess(dict):\n data = pd.DataFrame.from_dict(dict, orient='index').T\n return data\n\ndef predict(features):\n preds = model.predict(features)\n return float(preds[0])\n\n\napp = Flask('diabetes-prediction')\n\n@app.route('/predict', methods=['POST'])\ndef predict_endpoint():\n input = request.get_json()\n features = preprocess(input)\n pred = predict(features)\n\n result = {\n\t 'diabetes_binary': pred\n }\n return jsonify(result)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0', port=9696)","repo_name":"hakymulla/Diabetes-ML-ps","sub_path":"Test/predict_local.py","file_name":"predict_local.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"18729928875","text":"import time as t\nfrom datetime import time\nfrom graph import *\nfrom priority_queue import *\n\n\ndef run(graph, key_node_start, key_node_goal, verbose=False, time_sleep=0):\n if key_node_start not in graph.getNodes() or key_node_goal not in graph.getNodes():\n print('Error: key_node_start \\'%s\\' or key_node_goal \\'%s\\' not exists!!' % (\n key_node_start, key_node_goal))\n else:\n # UCS uses priority queue, priority is the cumulative cost (smaller cost)\n queue = PriorityQueue()\n\n # expands initial node\n\n # get the keys of all successors of initial node\n keys_successors = graph.getSuccessors(key_node_start)\n\n # adds the keys of successors in priority queue\n for key_sucessor in keys_successors:\n weight = graph.getWeightEdge(key_node_start, key_sucessor)\n # each item of queue is a tuple (key, cumulative_cost)\n queue.insert((key_sucessor, weight), weight)\n\n reached_goal, cumulative_cost_goal = False, -1\n while not queue.is_empty():\n # remove item of queue, remember: item of queue is a tuple (key, cumulative_cost)\n key_current_node, cost_node = queue.remove()\n if(key_current_node == key_node_goal):\n reached_goal, cumulative_cost_goal = True, cost_node\n break\n\n if verbose:\n # shows a friendly message\n if cost_node > 60:\n hours = int(cost_node)\n minutes = (cost_node * 60) % 60\n print('Expands node \\'%s\\' with cumulative time spent %s:%s ...' %\n (key_current_node, str(hours), str(minutes)))\n t.sleep(time_sleep)\n elif cost_node < 10:\n hours = '00'\n str_min = str(cost_node)\n minutes = str_min.zfill(2)\n print('Expands node \\'%s\\' with cumulative time spent %s:%s ...' %\n (key_current_node, hours, minutes))\n t.sleep(time_sleep)\n else:\n hours = '00'\n print('Expands node \\'%s\\' with cumulative time spent %s:%s ...' %\n (key_current_node, hours, str(cost_node)))\n t.sleep(time_sleep)\n\n # get all successors of key_current_node\n keys_successors = graph.getSuccessors(key_current_node)\n\n if keys_successors: # checks if contains successors\n # insert all successors of key_current_node in the queue\n for key_sucessor in keys_successors:\n cumulative_cost = graph.getWeightEdge(\n key_current_node, key_sucessor) + cost_node\n queue.insert((key_sucessor, cumulative_cost),\n cumulative_cost)\n\n if(reached_goal):\n if cumulative_cost_goal > 60:\n hours = int(cumulative_cost_goal)\n minutes = (cumulative_cost_goal * 60) % 60\n print('\\nReached goal! Time: %s:%s ...' %\n (str(hours), str(minutes)))\n elif cost_node < 10:\n hours = '00'\n str_min = str(cumulative_cost_goal)\n minutes = str_min.zfill(2)\n print('\\nReached goal! Time: %s:%s ...' %\n (hours, minutes))\n else:\n hours = '00'\n print('\\nReached goal! Time: %s:%s ...' %\n (hours, str(cumulative_cost_goal)))\n else:\n print('\\nUnfulfilled goal.\\n')\n\n\nif __name__ == \"__main__\":\n\n # build the graph...\n\n # adds nodes in the graph\n graph = Graph()\n graph.addNode('S') # start\n graph.addNode('a')\n graph.addNode('b')\n graph.addNode('c')\n graph.addNode('d')\n graph.addNode('e')\n graph.addNode('f')\n graph.addNode('G') # goal\n graph.addNode('h')\n graph.addNode('p')\n graph.addNode('q')\n graph.addNode('r')\n # linking the nodes\n graph.connect('S', 'd', time(0, 3, 0))\n graph.connect('S', 'e', time(0, 9, 0))\n graph.connect('S', 'p', time(0, 1, 0))\n graph.connect('b', 'a', time(0, 2, 0))\n graph.connect('c', 'a', time(0, 2, 0))\n graph.connect('d', 'b', time(0, 1, 0))\n graph.connect('d', 'c', time(0, 8, 0))\n graph.connect('d', 'e', time(0, 2, 0))\n graph.connect('e', 'h', time(0, 8, 0))\n graph.connect('e', 'r', time(0, 2, 0))\n graph.connect('f', 'c', time(0, 3, 0))\n graph.connect('f', 'G', time(0, 2, 0))\n graph.connect('h', 'p', time(0, 4, 0))\n graph.connect('h', 'q', time(0, 4, 0))\n graph.connect('p', 'q', time(0, 15, 0))\n graph.connect('r', 'f', time(0, 1, 0))\n\n run(graph=graph, key_node_start='S',\n key_node_goal='G', verbose=True, time_sleep=2)\n","repo_name":"kalebda/Uniform-Cost-Search","sub_path":"source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"19587928499","text":"#! /usr/bin/env python3\n# Coursera Project 2\n# Developed by XZANATOL\n\n# Imports\nimport os\nimport requests\n\ndef get_reqquest_dictionary(file):\n \"\"\"Returns a parsed dictionary of the feedback text file\"\"\"\n with open(file, \"r\") as file:\n # Read all lines and remove \\n character\n lines = file.readlines()\n for i in range(len(lines)):\n lines[i] = lines[i].rstrip(\"\\n\")\n\n return {\"title\": lines[0], \"name\": lines[1], \"date\": lines[2], \"feedback\": \" \".join(lines[3:])}\n\ndef send_request(dict):\n \"\"\"Send the dictionary to the Django webserver\"\"\"\n response = requests.post(\"http:///feedback/\", json=dict) # Replace by the ip address of the machine\n\n if not response.ok:\n print(\"[-] send failed with status code\", response.status_code)\n else:\n print(\"[+] send succeeded with status code\", response.status_code)\n\n# Execution begins here\nif __name__ == '__main__':\n\n #Debug output (name of file. dictionary parse, send status code) else can't open name of file\n\n for i in os.listdir(\"/data/feedback/\"):\n try:\n dict_to_send = get_reqquest_dictionary(\"/data/feedback/\"+i)\n print(\"\")\n print(i, \"\\n\", dict_to_send)\n send_request(dict_to_send)\n except:\n print(\"\\ncan't open\", i)\n\n# IT WORKED FROM THE FIRST SUBMIT WOOHOO!, just make sure you name the file \"run.py\" cuz i submitted it with name \"send.py\" till i noticed this error...","repo_name":"XZANATOL/ProjectSpace","sub_path":"Courses & Scholarships/2020_Google_IT_Python_Automation_6th_Course/Project 2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"11619849908","text":"import torch\n\nfrom dcfr.models.fair_repr import FairRepr\nfrom dcfr.utils.loss import weighted_cross_entropy, weighted_mse\nfrom dcfr.utils.mlp import MLP\n\n\nclass DCFR(FairRepr):\n def __init__(self, config, n_fair):\n super(DCFR, self).__init__(\"DCFR\", config)\n\n self.encoder = MLP(\n [config[\"xdim\"]] + config[\"encoder\"] + [config[\"zdim\"]], \"relu\"\n )\n self.prediction = MLP(\n [config[\"zdim\"]] + config[\"prediction\"] + [config[\"ydim\"]],\n \"relu\",\n )\n\n self.audit = MLP(\n [config[\"zdim\"] + n_fair] + config[\"audit\"] + [config[\"sdim\"]],\n \"relu\",\n )\n\n def forward_y(self, x):\n z = self.forward_z(x)\n y = self.prediction(z)\n y = torch.sigmoid(y)\n return y\n\n def forward_s(self, x, f):\n z = self.forward_z(x)\n s = self.audit(torch.cat([z, f], dim=1))\n s = torch.sigmoid(s)\n return s\n\n def forward_z(self, x):\n z = torch.nn.functional.relu(self.encoder(x))\n return z\n\n def forward(self, x):\n self.forward_y(x)\n\n def loss_prediction(self, x, y, w):\n y_pred = self.forward_y(x)\n loss = weighted_cross_entropy(w, y, y_pred)\n return loss\n\n def loss_audit(self, x, s, f, w):\n s_pred = self.forward_s(x, f)\n loss = weighted_mse(w, s, s_pred)\n return loss\n\n def weight_audit(self, df_old, s, f):\n df = df_old.copy()\n df[\"w\"] = 0.0\n\n if self.task == \"DP\":\n df[\"n_f\"] = df.shape[0]\n else:\n res = df.groupby(f).count()[\"w\"].reset_index().rename(columns={\"w\": \"n_f\"})\n df = df.merge(res, on=f, how=\"left\")\n\n res = (\n df.groupby(f + [s])\n .count()[\"w\"]\n .reset_index()\n .rename(columns={\"w\": \"n_s_f\"})\n )\n df = df.merge(res, on=f + [s], how=\"left\")\n\n df[\"w\"] = 1 - df[\"n_s_f\"] / df[\"n_f\"]\n\n res = torch.from_numpy(df[\"w\"].values).view(-1, 1)\n res = res / res.sum()\n return res\n\n def predict_only(self):\n self.audit.freeze()\n self.prediction.activate()\n self.encoder.activate()\n\n def audit_only(self):\n self.audit.activate()\n self.prediction.freeze()\n self.encoder.freeze()\n\n def finetune_only(self):\n self.audit.freeze()\n self.prediction.activate()\n self.encoder.freeze()\n\n def predict_params(self):\n return list(self.prediction.parameters()) + list(self.encoder.parameters())\n\n def audit_params(self):\n return self.audit.parameters()\n\n def finetune_params(self):\n return self.prediction.parameters()\n","repo_name":"windxrz/DCFR","sub_path":"dcfr/models/dcfr.py","file_name":"dcfr.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"80"} +{"seq_id":"28703935001","text":"\"\"\" Annulus geometry\n\n one layer case\n\n\"\"\"\nimport numpy as np\nfrom parameters import Param\nfrom grid import Grid\nfrom rsw import RSW\n\nparam = Param()\n\nreso = 2\nparam.expname = \"annulus\"\nparam.nz = 1\nparam.ny = 128*reso\nparam.nx = 128*reso\nparam.Lx = 2.\nparam.Ly = 1.\nparam.auto_dt = False\nparam.geometry = \"perio_y\"\nparam.coordinates = \"cylindrical\"\nparam.cfl = 0.2\nparam.dt = 0.8e-2/reso\nparam.tend = 5 # 0*param.dt\nparam.plotvar = \"h\"\nparam.freq_plot = 50\nparam.freq_his = 0.1\nparam.plot_interactive = True\nparam.plot_type = \"pcolormesh\"\nparam.colorscheme = \"auto\"\nparam.cax = np.asarray([-2e-4, 12e-4])/2\nparam.generate_mp4 = False\nparam.timestepping = \"RK3_SSP\"\nparam.f0 = 5.\nparam.var_to_save = [\"h\", \"vor\"]\n\n\ndef vortex(xx, yy, **kwargs):\n \"\"\"\n analytical function that defines the domain\n\n fmsk < 0 : solid\n fmsk == 0: boundary\n fmsk > 0 : fluid\n \"\"\"\n x0 = kwargs[\"x0\"]\n y0 = kwargs[\"y0\"]\n d = kwargs[\"d\"]\n vtype = kwargs[\"vtype\"]\n if \"ratio\" in kwargs:\n ratio = kwargs[\"ratio\"]\n else:\n ratio = 1.\n d2 = (xx-x0)**2*ratio + (yy-y0)**2\n if vtype == \"cosine\":\n d0 = np.sqrt(d2)\n m = np.cos(d0/d*(np.pi/2))\n m[d0 > d] = 0.\n else:\n m = np.exp(-d2/(2*d**2))\n return m\n\n\ngrid = Grid(param)\n\nxc, yc = grid.xc, grid.yc\nxe, ye = grid.xe, grid.ye\n\n\ngrid.finalize()\n\nmodel = RSW(param, grid)\n\n\nh = model.state.h\narea = grid.arrays.vol.view(\"i\")\nu = model.state.ux\nv = model.state.uy\n\nh0 = param.H\ng = param.g\nf = param.f0\n\n# setup initial conditions\n\nd = 0.1 # vortex radius\ndsep = -d*1.1 # half distance between the two vortices\n# the vortex amplitude controls the Froude number\namp = 0.1\n\n\ny0 = 0.5\nsigma = 0.08\n\nh[0] = h0-amp*(0.5+0.5*np.tanh((yc-y0)/sigma))\n\n\n# convert height \"h\" to a volume form, i.e. multiply with the cell area\nh[0] *= area\n\n# for k in range(param.nz):\n# h[k] *= msk\n\n# to set initial geostropic adjustement\n# define exactly the same height but at corner cells...\n# trick: we use the vorticity array because it has the good shape\n# this array will be overwritten with the true vorticity\n# once the model is launched\nhF = model.state.vor\nhF[0] = h0-amp*(0.5+0.5*np.tanh((ye-y0)/sigma))\n\n\ndef grad(phi, dphidx, dphidy):\n phi.setview(\"i\")\n dphidx.setview(\"i\")\n dphidx[:] = phi[..., 1:]-phi[..., :-1]\n phi.setview(\"j\")\n dphidy.setview(\"j\")\n dphidy[:] = phi[..., 1:]-phi[..., :-1]\n\n\nu[:] = 0.\nv[:] = 0.\n# then take the rotated gradient of it\n# grad(hF, v, u)\n# u[:] *= -(g/param.f0)\n# v[:] *= +(g/param.f0)\n\n\nu = model.state.ux.view(\"i\")\nv = model.state.uy.view(\"j\")\n\nmsku = grid.msku()\nmskv = grid.mskv()\n\nfor k in range(param.nz):\n u[k] *= msku\n v[k] *= mskv\n\nhF[:] = 0.\nmodel.run()\n","repo_name":"pvthinker/pyRSW","sub_path":"experiments/dambreak/annulus.py","file_name":"annulus.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"80"} +{"seq_id":"28150007512","text":"import discord\nfrom discord.ext import commands\nimport os\nimport sys\nsys.path.append(os.path.realpath('.'))\nimport config\nimport globalconfig\nclass Help(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.group(invoke_without_command=True)\n async def help(self, ctx):\n if ctx.invoked_subcommand is None:\n em = discord.Embed(title = \"Help\", description = \"Use `\" + config.prefix + \"help ` for extended information on a command.\", color = discord.Color.blue())\n em.add_field(name = \"General\", value = \"about\")\n em.add_field(name = \"Moderation\", value = \"ban, changenick, delwarn, kick, modnick, mute, purge, unban, unmute, warn, warns\")\n em.add_field(name = \"Settings\", value = \"botstatus, botstatusrepeat\")\n em.add_field(name = \"Utils\", value = \"avatar, joined, ping, quickpoll, uptime, userinfo\")\n em.add_field(name = \"Fun\", value = \"add, choose, f, emote, image\")\n em.add_field(name = \"Caesarcrypt\", value = \"twisted_msg, untwisted_msg\")\n em.add_field(name = \"VirusTotal\", value = \"scanurl, checkhash\")\n em.add_field(name = \"Update\", value = \"updatecheck, updatebot, updatecogs\")\n em.add_field(name = \"Admin\", value = \"getchannels, getinvite, loadcog, lockdownbot, reloadcog, restartbot, servers, shutdownbot, unloadcog\")\n em.add_field(name = \"Help\", value = \"help, changelog\")\n if config.latest_version > globalconfig.version:\n em.add_field(name = \"Notice\", value = \"This bot has an available update that will update it from version `\" + globalconfig.version + \"` to version `\" + config.latest_version + \"`. Please use `\" + config.prefix + \"updatecheck` for more details.\")\n elif config.latest_version < globalconfig.version:\n em.add_field(name = \"Notice\", value = \"This bot has an available downgrade that will downgrade it from version `\" + globalconfig.version + \"` to version `\" + config.latest_version + \"`. Please use `\" + config.prefix + \"updatecheck` for more details.\")\n await ctx.send(embed = em)\n\n # Moderation commands\n @help.command(name=\"ban\")\n async def _ban(self, ctx):\n em = discord.Embed(title = \"Moderation: Ban\", description = config.prefix + \"ban optional: \\n\\nBan a member.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n \n @help.command(name=\"changenick\")\n async def _changenick(self, ctx):\n em = discord.Embed(title = \"Moderation: ChangeNick\", description = config.prefix + \"changenick \\n\\nChanges the nickname of a user or a bot.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"delwarn\")\n async def _delwarn(self, ctx):\n em = discord.Embed(title = \"Moderation: Delwarn\", description = config.prefix + \"delwarn \\n\\nDelete a warning.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"kick\")\n async def _kick(self, ctx):\n em = discord.Embed(title = \"Moderation: Kick\", description = config.prefix + \"kick optional: \\n\\nKick a member.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n \n @help.command(name=\"modnick\")\n async def _modnick(self, ctx):\n em = discord.Embed(title = \"Moderation: ModNick\", description = config.prefix + \"modnick \\n\\nModerates the nickname of a user or a bot (sets the nickname to 'ModdedNick' plus a random string of letters or numbers).\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"mute\")\n async def _mute(self, ctx):\n em = discord.Embed(title = \"Moderation: Mute\", description = config.prefix + \"mtue \\n\\nMute a member.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"purge\")\n async def _purge(self, ctx):\n em = discord.Embed(title = \"Moderation: Purge\", description = config.prefix + \"purge \\n\\nPurge messages, default amount is 10.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"unban\")\n async def _unban(self, ctx):\n em = discord.Embed(title = \"Moderation: Unban\", description = config.prefix + \"unban \\n\\nUnban a member.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"unmute\")\n async def _unmute(self, ctx):\n em = discord.Embed(title = \"Moderation: Unmute\", description = config.prefix + \"unmute \\n\\nUnmute a member.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"warn\")\n async def _warn(self, ctx):\n em = discord.Embed(title = \"Moderation: Warn\", description = config.prefix + \"warn \\n\\nWarn a member.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"warns\")\n async def _warns(self, ctx):\n em = discord.Embed(title = \"Moderation: Warns\", description = config.prefix + \"warns \\n\\nSee the warnings for a member.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n # General commands\n @help.command(name=\"about\")\n async def _about(self, ctx):\n em = discord.Embed(title = \"General: About\", description = config.prefix + \"about \\n\\nShows information about this bot instance.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n # Fun commands\n @help.command(name=\"add\")\n async def _add(self, ctx):\n em = discord.Embed(title = \"Fun: Add\", description = config.prefix + \"add \\n\\nAdds two numbers together.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"choose\")\n async def _choose(self, ctx):\n em = discord.Embed(title = \"Fun: Choose\", description = config.prefix + \"choose \"\" \"\" \\n\\nChooses between multiple choices.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"f\")\n async def _f(self, ctx):\n em = discord.Embed(title = \"Fun: F\", description = config.prefix + \"f \\n\\nSays F in the chat and adds an F emoji to the message.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"emote\")\n async def _emote(self, ctx):\n em = discord.Embed(title = \"Fun: Emote\", description = config.prefix + \"emote \\n\\nEmote command.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n \n @help.command(name=\"image\")\n async def _image(self, ctx):\n em = discord.Embed(title = \"Fun: Image\", description = config.prefix + \"image \\n\\nSearches an image up on the internet and sends it on Discord.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"clearcache\")\n async def _clearcache(self, ctx):\n em = discord.Embed(title = \"Fun: ClearCache\", description = config.prefix + \"clearcache \\n\\nClears the cache of an image search. This will make the cache file regenerate on the next image search.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"listcache\")\n async def _listcache(self, ctx):\n em = discord.Embed(title = \"Fun: ListCache\", description = config.prefix + \"listcache \\n\\nLists the cache files of the image searches.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n\n # Settings commands\n @help.command(name=\"botstatus\")\n async def _botstatus(self, ctx):\n em = discord.Embed(title = \"Settings: BotStatus\", description = config.prefix + \"botstatus \\n\\nSets the status of the bot. Owner only. '\" + config.prefix + \"botstatus' to reset\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"botstatusrepeat\")\n async def _botstatusrepeat(self, ctx):\n em = discord.Embed(title = \"Settings: BotStatusRepeat\", description = config.prefix + \"botstatusrepeat \\n\\nRepeatedly sets the status of the bot. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n # Utils commands\n @help.command(name=\"avatar\")\n async def _avatar(self, ctx):\n em = discord.Embed(title = \"Utils: Avatar\", description = config.prefix + \"avatar \\n\\nGet a link to somebody's avatar.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"joined\")\n async def _joined(self, ctx):\n em = discord.Embed(title = \"Utils: Joined\", description = config.prefix + \"joined \\n\\nTells you when a user joined the server.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"ping\")\n async def _ping(self, ctx):\n em = discord.Embed(title = \"Utils: Ping\", description = config.prefix + \"ping \\n\\nTells you the latency between the bot and the server.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"quickpoll\")\n async def _quickpoll(self, ctx):\n em = discord.Embed(title = \"Utils: Quickpoll\", description = config.prefix + \"quickpoll \\n\\nMake a poll with yes/no reactions.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"uptime\")\n async def _uptime(self, ctx):\n em = discord.Embed(title = \"Utils: Uptime\", description = config.prefix + \"uptime \\n\\nShows the uptime of the bot.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"userinfo\")\n async def _userinfo(self, ctx):\n em = discord.Embed(title = \"Utils: Userinfo\", description = config.prefix + \"userinfo \\n\\nGives you information about a user.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n # Caesar commands\n @help.command(name=\"twisted_msg\")\n async def _encrypt(self, ctx):\n em = discord.Embed(title = \"Caesarcrypt: Twisted Your Message\", description = config.prefix + \"twisted_msg \\n\\nTwisted a message.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"untwisted_msg\")\n async def _decrypt(self, ctx):\n em = discord.Embed(title = \"Caesarcrypt: Untwisted Your Message\", description = config.prefix + \"untwisted_msg \\n\\nUntwisted a message.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n # Update commands\n @help.command(name=\"updatebot\")\n async def _updatebot(self, ctx):\n em = discord.Embed(title = \"Update: UpdateBot\", description = config.prefix + \"updatebot \\n\\nUpdates/downgrades the bot, replacing all of the bot files, except for the warns folder and the config.py file, with the newest files directly from the GitHub repository. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"updatecheck\")\n async def _updatecheck(self, ctx):\n em = discord.Embed(title = \"Update: UpdateCheck\", description = config.prefix + \"updatecheck \\n\\nChecks for updates/downgrades for the bot. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"updatecogs\")\n async def _updatecogs(self, ctx):\n em = discord.Embed(title = \"Update: UpdateCogs\", description = config.prefix + \"updatecogs \\n\\nUpdates the bot's cogs, replacing all of the cog files with the newest files directly from the GitHub repository. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n # VirusTotal commands\n @help.command(name=\"scan_url\")\n async def _scan_url(self, ctx):\n em = discord.Embed(title = \"VirusTotal: Scan_URL\", description = config.prefix + \"scan_url with https or http at the begining \\n\\nScans a URL link using a VirusTotal API key.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"vt_hash\")\n async def _vt_hash(self, ctx):\n em = discord.Embed(title = \"VirusTotal: VT_Hash\", description = config.prefix + \"vt_hash SHA-256 SHA-1 or MD5 \\n\\nScans a file hash using a VirusTotal API key.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n # Owner commands\n @help.command(name=\"loadcog\")\n async def _reloadcog(self, ctx):\n em = discord.Embed(title = \"Owner: LoadCog\", description = config.prefix + \"loadcog \\n\\nLoads the user specified cog. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"lockdownbot\")\n async def _lockdownbot(self, ctx):\n em = discord.Embed(title = \"Owner: LockdownBot\", description = config.prefix + \"lockdownbot \\n\\nLocks down the bot in all servers and disables most commands. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"reloadcog\")\n async def _reloadcog(self, ctx):\n em = discord.Embed(title = \"Owner: ReloadCog\", description = config.prefix + \"reloadcog \\n\\nReloads the user specified cog. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"restartbot\")\n async def _restartbot(self, ctx):\n em = discord.Embed(title = \"Owner: RestartBot\", description = config.prefix + \"restartbot \\n\\nRestarts the bot. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"shutdownbot\")\n async def _shutdownbot(self, ctx):\n em = discord.Embed(title = \"Owner: ShutdownBot\", description = config.prefix + \"shutdownbot \\n\\nShuts down the bot. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"unloadcog\")\n async def _reloadcog(self, ctx):\n em = discord.Embed(title = \"Owner: UnloadCog\", description = config.prefix + \"unloadcog \\n\\nUnloads the user specified cog. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"servers\")\n async def _servers(self, ctx):\n em = discord.Embed(title = \"Owner: Servers\", description = config.prefix + \"servers \\n\\nProvides a list of servers the bot is in, along with server IDs. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"getchannels\")\n async def _getchannels(self, ctx):\n em = discord.Embed(title = \"Owner: GetChannels\", description = config.prefix + \"getchannels \\n\\nGets the channels of the server provided. The bot must be in the server for this to work. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\n @help.command(name=\"getinvite\")\n async def _getinvite(self, ctx):\n em = discord.Embed(title = \"Owner: GetInvite\", description = config.prefix + \"getinvite \\n\\nGenerates an invite for the server provided. A channel name can optionally be provided and it defauts to `general`. Owner only.\", color = discord.Color.blue())\n await ctx.send(embed = em)\n\ndef setup(bot):\n bot.add_cog(Help(bot))\n","repo_name":"PrimarineRose/freediscord","sub_path":"cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":15288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"11090051630","text":"#-- coding: utf-8 _*_\n\nr\"\"\"\n @Copyright 2022\n The Intelligent Data Analysis, in DKU. All Rights Reserved.\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as torchmodel\n\nr\"\"\"\n [Examples]\n\"\"\"\n\nclass WDHT(nn.Module):\n\n r\"\"\"\n Return the torch modules, contatining WDHT.\n Args:\n back_bone\n \"\"\"\n\n def __init__(self, back_bone, hash_bit, feature_num):\n super(WDHT, self).__init__()\n \n self.back_bone = back_bone\n self.hash_bit = hash_bit\n self.feature_num = feature_num\n \n self.total_linear_1 = nn.Linear(2048,2048)\n self.total_linear_2 = nn.Linear(2048, 256)\n self.hashing_linear = nn.Linear(256, hash_bit)\n self.classifier_linear = nn.Linear(256, feature_num)\n self.back_bone_linear = nn.Linear(2048,2048)\n\n def forward(self, input_data):\n self.back_bone.fc = self.back_bone_linear\n x = F.relu(self.back_bone(input_data))\n x = F.relu(self.total_linear_1(x))\n x = F.relu(self.total_linear_2(x))\n hash_layer = F.tanh(self.hashing_linear(x))\n classify_layer = F.tanh(self.classifier_linear(x))\n\n return classify_layer, hash_layer\n\n def freeze(self):\n for params in self.back_bone.parameters():\n params.requires_grad = False\n\n def init(self,method='he_uniform'):\n \n if method == 'he_uniform':\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n nn.init.kaiming_uniform_(m.weight, mode='fan_in', nonlinearity='leaky_relu')\n \n elif method == 'glorot_uniform':\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n\ndef LoadBackbone(load_name,pretrain=True):\n \n if load_name == 'resnet50':\n return torchmodel.resnet50(pretrained=pretrain)#.to('cuda')\n\n elif load_name == 'resnet18':\n return torchmodel.resnet18(pretrained=pretrain)\n \n elif load_name == 'vgg16':\n return torchmodel.vgg16(pretrained=pretrain)\n\n else:\n raise KeyError\n","repo_name":"IDASooinKim/WDHT","sub_path":"model/WDHT.py","file_name":"WDHT.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"36632532370","text":"from cards import *\n\nclass player:\n\tdef __init__(self, cardList):\n\t\tself.hand = hand(cardList)\n\t\tself.tricks = []\n\t\tself.numTricks = 0\n\t\tself.score = 0\n\t\tself.has2C = query2C()\n\n\tdef query2C(self):\n\t\tthisHand = self.hand.getHand()\n\t\tfor card in thisHand:\n\t\t\tif card.getName() == \"2C\":\n\t\t\t\treturn(True)\n\t\treturn(False)\n\n\tdef takeTrick(self, cardList):\n\t\tself.numTricks += 1\n\t\tself.tricks.extend(cardList)\n\n\tdef legalMoves(self):\n\t\t\n\t\tthisHand = self.hand.getHand()\n\t\tlegalMoves = []\n\n\t\t# If this player is leading the trick\n\t\tif leadingCard == None:\n\t\t\t# if hearts have been broken, anything can be played\n\t\t\tif heartsBroken:\n\t\t\t\tfor card in thisHand:\n\t\t\t\t\tlegalMoves.append(card.getName())\n\t\t\t# if hearts haven't been broken, any non-heart can be played\n\t\t\telse:\n\t\t\t\tfor card in thisHand:\n\t\t\t\t\tif card.getSuit() != \"H\":\n\t\t\t\t\t\tlegalMoves.append(card.getName())\n\n\t\t# If the player is not leading the trick\n\t\telse:\n\n\t\t\t# Add all cards of the same type as the leading card\n\t\t\tfor card in thisHand:\n\t\t\t\tif card.getSuit() == leadingCard.getSuit():\n\t\t\t\t\tlegalMoves.append(card.getName())\n\n\t\t\t# If there are no cards of the same type, any card can be played\n\t\t\tif legalMoves == []:\n\t\t\t\tfor card in thisHand:\n\t\t\t\t\tlegalMoves.append(card.getName())\n\t\treturn(legalMoves)\n\n\t\tdef selectCard(self):\n\t\t\tmoves = self.legalMoves()\n\t\t\treturn(legalMoves[randint(0,len(moves))])\n\n\n\tdef play(self, cardName):\n\t\treturn(self.hand.play(cardName))\n\n# Create deck and shuffle\ndeck = deck()\ndeck.shuffle()\n\t\t\n# Create players\nplayers = [player(deck.deal(13)) for i in range(0,4)]\n\n# Initialize global variables\nleadingCard = '2C'\nheartsBroken = False\ntookLastTrick = 0 # integer 0-3, representing which player took the last trick\nplaying = True\n\n# Player with 2C leads first trick\nfor player in players:\n\tif player.query2C() == True:\n\t\tplayer.play('2C')\n\t\tbreak\n\ttookLastTrick += 1\n\n\nleadingCard = None # For test purposes, the leading card has not been chosen. \n# Second trick and onward\nwhile playing:\n\t# Start from the player who took the last trick\n\tfor i in [tookLastTrick, (tookLastTrick+1)%4, (tookLastTrick+2)%4, (tookLastTrick+3)%4]:\n\t\t# Make a move\n\t\tmove = players[i].selectCard()\n\t\t# If the player is leading the trick, record the card (s)he played. \n\t\tif i == tookLastTrick:\n\t\t\tleadingCard = move.getName()\n\n\n\n\n\n\n\n# Test script\nplayers[0].hand.printHand()\nprint(players[0].legalMoves())","repo_name":"syeomans/cards","sub_path":"Hearts.py","file_name":"Hearts.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"29713371037","text":"BASE_DIRECTORY = '/home/app'\nDOMAIN_URL = 'http://www.example.com'\nPRETTY_DOMAIN_URL = 'Example.com'\n\nPYTHON_DIRECTORY = '/usr/bin/python'\nAPP_DIRECTORY = '/app'\nAPP_NAME = 'App Name'\n\nMYSQL_DATABASE_URI = 'mysql+mysqlconnector://:@:/'\nLAST_DB_UPDATE = ''\n\nAPI_KEY = ''\n\nAPP_SECRET = ''\n\nADMIN_USERS = []\n\nGOOGLE_ANALYTICS = ''\n\nBITCOIN_ADDRESS = ''\n\nDEBUG_ACTIVE_P = False\n\nSUPPORT_EMAIL = ''\nFB_ADMIN_USERS = '000000' # Used to assign site ownership on Facebook\nAUTHOR = {\n 'NAME':'',\n 'WEBSITE':'',\n 'HANDLE':'',\n 'SOCIAL_PROFILE':{\n 'FACEBOOK':'',\n 'TWITTER':'',\n 'LINKEDIN':'',\n 'GOOGLEPLUS':'',\n 'STEAM':''\n }\n}\n\nMAINTENANCE_ACTIVE_P = False # Toggles hiding the search box and displaying the maintenance message\n\nDISABLE_INDEXING_P = True # Toggles search engine indexing\n","repo_name":"jprusik/steam-gauge","sub_path":"app/config-example.py","file_name":"config-example.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"80"} +{"seq_id":"34829726737","text":"\"\"\"\nDeconvolution with pymc3 as MCMC sampler and forward model based on the\nanalytical solution of the detector model's governing equations\n\"\"\"\n\n# Set flags for theano\n# ref: http://deeplearning.net/software/theano_versions/dev/faq.html#faster-theano-function-compilation\n# ideas for compiling more quickly\n# ref: https://github.com/Theano/Theano/issues/4494\nimport os\n\ntheano_flags = [\"cycle_detection=fast,optimizer_excluding=inplace_elemwise_optimizer\"]\n# theano_flags = [\"mode=FAST_COMPILE\"]\nos.environ[\"THEANO_FLAGS\"] = \",\".join(theano_flags)\n\n\n# theano sometimes breaks recursion limits\n# ref: https://github.com/Theano/Theano/issues/689\nimport sys\n\nsys.setrecursionlimit(50000)\n\nimport numpy as np\nimport theano\nimport theano.tensor as tt\nimport datetime\nimport xarray as xr\nimport arviz\n\n# theano.compile.DebugMode = True\n# theano.config.mode = 'FAST_COMPILE'\n\nfrom .forward_model import convolve_radon_timeseries, convolve_radon_timeseries_numpy\nfrom scipy.stats import distributions\n\nimport pymc3 as pm\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n# timing helper\nfrom contextlib import contextmanager\nimport time as timelib\n\nlamrn = 2.100140526711101e-06\n\nclass DeconvolutionError(Exception):\n pass\n\n\n@contextmanager\ndef timing(description: str) -> None:\n start = timelib.time()\n yield\n elapsed_time = timelib.time() - start\n logger.info(f\"{description} took {round(elapsed_time, 1)} seconds\")\n\n\ndef fit_model_to_obs(\n time: np.ndarray,\n counts: np.ndarray,\n detector_params: dict,\n known_radon: np.ndarray = None,\n Nsamples: int = 1000,\n Nchains: int = 4,\n njobs: int = 4,\n figure_manager=None,\n):\n if njobs is None:\n njobs = 1\n with timing(\"Constructing model\"):\n model = construct_model(\n time=time,\n counts=counts,\n detector_params=detector_params,\n known_radon=known_radon,\n )\n try:\n with timing(f\"MCMC diagnostics\"):\n logger.debug(f\"Test point logp:\\n{model.check_test_point()}\")\n with model:\n map_estimate = pm.find_MAP(progressbar=(njobs > 1))\n logger.debug(\"MAP estimate:\")\n for k in map_estimate.keys():\n if not k in [\"logradon\", \"radon\", \"E_simulated_counts\"]:\n if k in detector_params:\n logger.debug(\n f\"{k}: {map_estimate[k]} (normalised by prior: {map_estimate[k]/detector_params[k]})\"\n )\n else:\n logger.debug(f\"{k}: {map_estimate[k]}\")\n if k == \"radon\":\n radon_str = \" \".join(\n [f\"{float(itm):.3}\" for itm in map_estimate[k]]\n )\n if len(radon_str) > 80:\n radon_str = radon_str[:80] + \"...\"\n logger.debug(f\"{k}: {radon_str}\")\n # This isn't doing what I want it to - disable for now\n # logger.debug(\n # f\"MAP estimate logp:\\n{model.check_test_point(test_point=map_estimate)}\"\n # )\n if True:\n # TODO: produce this plot and save to a file\n # perhaps via a 'figure manager' class which\n # knows where to save the figure, and keeps track\n # of a figure counter\n # plot MAP estimate\n fig, ax = plt.subplots()\n delta_t = time[1] - time[0]\n\n ax.plot(\n time / 3600.0,\n counts / delta_t / detector_params[\"total_efficiency\"],\n label=\"scaled counts\",\n )\n ax.plot(\n time / 3600.0,\n map_estimate[\"E_simulated_counts\"]\n / delta_t\n / detector_params[\"total_efficiency\"],\n label=\"scaled counts (simulated)\",\n )\n ax.plot(time / 3600, map_estimate[\"radon\"], label=\"reconstructed radon\")\n ax.legend()\n\n if figure_manager is not None:\n figure_manager.save_figure(fig, \"map\")\n\n # plt.show()\n\n with timing(f\"MCMC sampling {Nchains} chains of {Nsamples} points each\"):\n with model:\n # assume we're running under dask if njobs == 1 and we need to\n # hide the progressbar\n progressbar = njobs > 1\n # default target_accept is 0.8. Increase (if needed) to make\n # sampling more robust\n # default number of tuning steps is tune=500\n ntune = min(500, Nsamples)\n trace = pm.sample(\n Nsamples,\n chains=Nchains,\n progressbar=progressbar,\n cores=njobs,\n # target_accept=0.9,\n tune=ntune,\n )\n\n except pm.parallel_sampling.ParallelSamplingError as pm_exception:\n logger.exception(pm_exception)\n logger.error(\"Checking test point, initial logp, and logp gradient evaluation\")\n logger.error(f\"Test point: {model.test_point}\")\n logger.error(f\"Test point logp: {model.check_test_point()}\")\n f = model.logp_dlogp_function()\n f.set_extra_values({})\n y = f(f.dict_to_array(model.test_point))\n logger.error(f\"logp gradient: {y}\")\n raise\n ret = {}\n ret[\"trace\"] = trace\n ret[\"map_estimate\"] = map_estimate\n return ret\n\n\ndef trace_as_xarray(index_time, trace, vn=\"deconvolved_radon\"):\n \"\"\"Convert pymc3 trace to xarray, dropping the less-useful bits\n \n Parameters\n ----------\n index_time : [type]\n Data to use for the time index\n trace : [type]\n pymc3 trace from inference\n \"\"\"\n ds = arviz.from_pymc3(trace).posterior\n # cleanup\n ds = ds.rename_dims({\"radon_dim_0\": \"time\"})\n ds = ds.rename_vars({\"radon_dim_0\": \"time\"})\n vars_to_drop = [\n \"logradon_dim_0\",\n \"logradon\",\n # \"E_simulated_counts\",\n \"E_simulated_counts_dim_0\",\n ]\n for k in vars_to_drop:\n if k in ds:\n ds = ds.drop(k)\n # create time variable - possibly with placeholder values\n if index_time is None:\n Ntime = len(ds.time)\n dt = datetime.timedelta(minutes=30)\n index_time = [datetime.datetime(1900, 1, 1) + ii * dt for ii in range(Ntime)]\n else:\n index_time = np.array(index_time)\n\n timevar = xr.DataArray(index_time, dims=[\"time\"])\n timevar.attrs[\"long_name\"] = \"Time at end of averaging period\"\n ds[\"time\"] = timevar\n\n return ds\n\n\ndef stats_from_xarray(ds):\n # analagous to a +/- one sigma interval\n # variable name root\n k = 'radon_deconv'\n summary_data = []\n mid = ds.stack(z=(\"chain\", \"draw\")).radon.mean(dim=\"z\")\n mid.name = k\n summary_data.append(mid)\n sd = ds.stack(z=(\"chain\", \"draw\")).radon.std(dim=\"z\")\n sd.name = k+'_sd'\n summary_data.append(sd)\n\n low_16pc, high_84pc = arviz.hpd(\n ds.stack(z=(\"chain\", \"draw\")).radon.T, credible_interval=0.68\n ).T\n low_16pc = xr.DataArray(low_16pc, dims=(\"time\",))\n low_16pc.name = k+\"_16pc\"\n high_84pc = xr.DataArray(high_84pc, dims=(\"time\",))\n high_84pc.name = k+\"_84pc\"\n summary_data.append(low_16pc)\n summary_data.append(high_84pc)\n\n low_3pc, high_97pc = arviz.hpd(\n ds.stack(z=(\"chain\", \"draw\")).radon.T, credible_interval=0.94\n ).T\n low_3pc = xr.DataArray(low_3pc, dims=(\"time\",))\n low_3pc.name = k+\"_3pc\"\n high_97pc = xr.DataArray(high_97pc, dims=(\"time\",))\n high_97pc.name = k+\"_97pc\"\n summary_data.append(low_3pc)\n summary_data.append(high_97pc)\n\n ds_ret = xr.merge(summary_data)\n try:\n ds_ret['overlap_flag'] = ds['overlap_flag']\n except KeyError:\n pass\n\n return ds_ret\n\n\ndef result_plot(ds, ax=None):\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = ax.figure\n t = ds.time\n ax.plot(t, ds.mcmc_mean.values, label=\"mean\")\n ax.fill_between(t, ds.mcmc_16pc, ds.mcmc_84pc, alpha=0.3, label=\"HPD 68%\")\n ax.fill_between(t, ds.mcmc_3pc, ds.mcmc_97pc, alpha=0.6, label=\"HPD 94%\")\n return fig, ax\n\n\ndef summarise_result(index_time, trace, vn=\"deconvolved_radon\"):\n pm_summary = pm.summary(trace)\n # TODO: extract only relevant information\n radon_summary = pm.summary(trace, var_names=[\"radon\"])\n cols_to_keep = [\"mean\", \"sd\", \"hpd_3%\", \"hpd_97%\", \"ess_mean\", \"r_hat\"]\n rename_dict = {}\n for k in cols_to_keep:\n rename_dict[k] = f\"{k}_{vn}\"\n rename_dict[\"mean\"] = vn\n radon_trace = trace[\"radon\"].copy()\n\n radon_summary = radon_summary[cols_to_keep].rename(columns=rename_dict)\n radon_summary.index = index_time\n radon_summary.index.name = \"time\"\n radon_summary[\"interval_end_time\"] = radon_summary.index.values\n dt = radon_summary[\"interval_end_time\"].diff().values[1]\n radon_summary[\"interval_start_time\"] = radon_summary[\"interval_end_time\"] - dt\n\n # 1d parameters that are not transformed\n inference_vars = [\n k for k in trace.varnames if len(trace[k].shape) == 1 and not k.endswith(\"__\")\n ]\n print(inference_vars)\n\n inference_vars_summary = pm.summary(trace, var_names=inference_vars)\n inference_vars_summary = inference_vars_summary[cols_to_keep].rename(\n columns=rename_dict\n )\n\n return pm_summary\n\n\ndef construct_model(\n time: np.ndarray,\n counts: np.ndarray,\n detector_params: dict,\n known_radon: np.ndarray = None,\n) -> pm.Model:\n\n # shorter variable name, as we use this a lot\n sp = detector_params\n # derived variables and flags\n Npts = len(counts)\n # note - theano doesn't handle boolean masks, hence the .nonzero()\n # ref: https://stackoverflow.com/questions/37425401/theano-tensor-slicing-how-to-use-boolean-to-slice\n flag_valid = np.isfinite(counts).nonzero()\n Npts_valid = len(counts[flag_valid])\n delta_t = time[1] - time[0]\n\n if time[0] == 0:\n logger.error(\n \"Time should not start at zero because timestamps should label the end of each counting interval\"\n )\n\n radon_conc_known = known_radon is not None\n smooth_radon_timeseries = \"expected_change_std\" in sp\n if not \"cal_source_strength\" in sp and not \"cal_duration\" in sp:\n simulate_calibration = False\n else:\n simulate_calibration = (sp[\"cal_source_strength\"] > 0) and (\n sp[\"cal_duration\"] > 0\n )\n\n if radon_conc_known:\n logger.info(\n \"Ambient radon concentration is known - configuring model to fit other parameters\"\n )\n else:\n logger.info(\"Configuring model to perform deconvolution\")\n logger.info(\n f\"Smoothing radon concentration timeseries: {smooth_radon_timeseries}\"\n )\n\n cal_injection_upstream_of_delay = detector_params.get(\n \"cal_injection_upstream_of_delay\", False\n )\n if simulate_calibration:\n inj_loc = [\"downstream\", \"upstream\"][int(cal_injection_upstream_of_delay)]\n logger.info(\n f\"Simulating calibration in model with injection {inj_loc} of external delay volume\"\n )\n\n if not np.allclose(np.diff(time), delta_t):\n raise ValueError(\"time must have uniform spacing\")\n\n try:\n background_count_rate = sp[\"background_rate\"]\n except KeyError:\n logger.warning(\"Background count rate not specified, assuming zero\")\n logger.warning(\"(Set 'background_rate' in cps to include background counts.)\")\n background_count_rate = 0.0\n\n logger.info(\n f\"Timeseries is {Npts} points long with {np.isnan(counts).sum()} NaN values\"\n )\n if Npts - np.isnan(counts).sum() < 1:\n raise DeconvolutionError('No valid data for deconvolution')\n\n logger.debug(f\"Timestep is {delta_t/60} minutes\")\n # Priors --\n # we'll express these with a lognormal distribution\n # but the sigma gets provided in terms of sigma/mu\n # for example, a 10% error (1-sigma range between mu/1.1 to mu*1.1)\n # implies a shape parameter of log(1.1)\n\n total_efficiency = sp[\"total_efficiency\"]\n # this is not presently in use\n total_efficiency_frac_error = 1.05\n\n Q_external_frac_error = 1.025\n rs = sp[\"rs\"]\n rs_frac_error = 1.025\n rn0_guess = counts[np.isfinite(counts)][0] / sp[\"total_efficiency\"] / delta_t\n # place a floor value on rn0\n rn0_guess = max(rn0_guess, 1 / sp[\"total_efficiency\"] / delta_t)\n rn0_frac_error = 1.25\n # radon - reference value (for scaling initial guess)\n rn_ref = (counts[np.isfinite(counts)].mean() / delta_t - background_count_rate) / sp[\"total_efficiency\"]\n\n # are we simulating a calibration?\n if simulate_calibration:\n # if we're calibrating, we don't know total eff very well\n total_efficiency_frac_error = 2.0\n # adjust rn_ref for calibration injection\n cal_increment = sp[\"cal_source_strength\"] / sp[\"Q_external\"] * lamrn\n rn_ref -= cal_increment * sp[\"cal_duration\"] / (time[-1] - time[0])\n\n # guard against rn_ref < 0\n if rn_ref <= 0:\n # don't subtract off the background\n rn_ref = (counts[np.isfinite(counts)].mean() / delta_t ) / sp[\n \"total_efficiency\"\n ]\n\n logger.debug(\n f\"Radon reference value is {rn_ref}, radon at t=0 (prior estimate) is {rn0_guess}\"\n )\n\n radon_detector_model = pm.Model()\n\n with radon_detector_model:\n if radon_conc_known:\n radon = pm.Constant(\"radon\", known_radon.astype(float), shape=(Npts,))\n else:\n if smooth_radon_timeseries:\n # radon timeseries (with smoothing prior)\n logradon = pm.GaussianRandomWalk(\n \"logradon\",\n shape=(Npts,),\n mu=0,\n sigma=np.log(sp[\"expected_change_std\"]),\n )\n radon = pm.Deterministic(\"radon\", rn_ref * pm.math.exp(logradon))\n else:\n # otherwise, just put radon somewhere close to its mean value\n # fix sigma and then use the relationship that, for\n # lognormal, E[x] = exp(mu + 1/2 sigma**2)\n # => mu = log(E[x]) - 1/2 sigma**2\n sigma_rn = np.log(2.0)\n mu_rn = np.log(rn_ref) - 0.5 * sigma_rn ** 2\n radon = pm.Lognormal(\"radon\", mu=mu_rn, sigma=sigma_rn, shape=(Npts,))\n\n # detector parameter priors\n # note: assuming that sigma << mu for Lognormal distributions\n # (alternative could be to use truncated normal)\n rs = pm.distributions.Lognormal(\n \"rs\", mu=np.log(rs), sigma=np.log(rs_frac_error)\n )\n rn0 = pm.distributions.Lognormal(\n \"rn0\",\n mu=np.log(rn0_guess) - 0.5 * np.log(rn0_frac_error) ** 2,\n sigma=np.log(rn0_frac_error),\n )\n\n if Q_external_frac_error > 0:\n Q_external = pm.distributions.Lognormal(\n \"Q_external\",\n mu=np.log(sp[\"Q_external\"]),\n sigma=np.log(Q_external_frac_error),\n )\n else:\n # Q_external is a constant\n Q_external = sp[\"Q_external\"]\n\n # params taken from \"sp\" take fixed values\n detector_params = {\n \"Q\": sp[\"Q\"],\n \"rs\": rs,\n \"lamp\": sp[\"lamp\"],\n \"Q_external\": Q_external,\n \"V_delay\": sp[\"V_delay\"],\n \"V_tank\": sp[\"V_tank\"],\n \"total_efficiency\": tt.as_tensor_variable(sp[\"total_efficiency\"]),\n \"num_delay_volumes\": sp[\"num_delay_volumes\"],\n }\n\n # if we are fitting to a calibration then the total efficiency is unknown\n if simulate_calibration:\n total_efficiency = pm.distributions.Lognormal(\n \"total_efficiency\",\n mu=np.log(sp[\"total_efficiency\"]),\n sigma=np.log(total_efficiency_frac_error),\n )\n # RVs for cal\n if sp[\"cal_begin_sigma\"] > 0:\n cal_begin = pm.Bound(pm.Normal, lower=0, upper=max(time))(\n \"cal_begin\", mu=sp[\"cal_begin\"], sigma=sp[\"cal_begin_sigma\"]\n )\n else:\n cal_begin = tt.as_tensor_variable(sp[\"cal_begin\"])\n if sp[\"cal_duration_sigma\"] > 0:\n cal_duration = pm.Bound(pm.Normal, lower=0)(\n \"cal_duration\",\n mu=sp[\"cal_duration\"],\n sigma=sp[\"cal_duration_sigma\"],\n )\n else:\n cal_duration = tt.as_tensor_variable(sp[\"cal_duration\"])\n detector_params[\"cal_begin\"] = cal_begin\n detector_params[\"cal_duration\"] = cal_duration\n detector_params[\"total_efficiency\"] = total_efficiency\n detector_params[\"cal_source_strength\"] = sp[\"cal_source_strength\"]\n\n # expected value of \"simulated counts\"\n E_simulated_counts = pm.Deterministic(\n \"E_simulated_counts\",\n convolve_radon_timeseries(\n t=time,\n radon=radon,\n radon_0=rn0,\n Npts=Npts,\n delta_t=delta_t,\n detector_params=detector_params,\n simulate_calibration=simulate_calibration,\n cal_injection_upstream_of_delay=cal_injection_upstream_of_delay,\n )\n + background_count_rate * delta_t,\n )\n pm.distributions.Poisson(\n \"counts\", mu=E_simulated_counts[flag_valid], observed=counts[flag_valid], shape=(Npts_valid,)\n )\n\n return radon_detector_model\n","repo_name":"agriff86/rd-deconvolve","sub_path":"rddeconv/pymc3_deconvolve.py","file_name":"pymc3_deconvolve.py","file_ext":"py","file_size_in_byte":17784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"28312652883","text":"\nclass Phone:\n def __init__(self) :\n self.os = None\n self.ram = None\n self.processor = None\n self.battery = None\n self.cam = None\n\n def __str__(self):\n return (\"The Phone details are - \\n OS: \"+ str(self.os) + \"\\n Processor: \" + str(self.processor) + \"\\n Battery: \" \\\n + str(self.battery) + \"\\n RAM: \" + str(self.ram) + \"\\n Camera: \" + str(self.cam) + \"\\n\")\n \n","repo_name":"AnkitaTandon/design-patterns","sub_path":"src/builder/phone.py","file_name":"phone.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"10580767555","text":"from pdb_services.data_api import entry_service\n\n\nclass TestEntryService:\n def test_entry(self):\n entry_id = \"1EHZ\"\n service = entry_service.EntryService()\n data = service.search(entry_id)\n cell_data = {\n \"angle_alpha\": 90.0,\n \"angle_beta\": 90.2,\n \"angle_gamma\": 90.0,\n \"length_a\": 54.981,\n \"length_b\": 33.389,\n \"length_c\": 61.921,\n \"zpdb\": 2,\n }\n assert data[\"cell\"] == cell_data\n\n def test_pubmed(self):\n entry_id = \"1US2\"\n service = entry_service.PubMedService()\n data = service.search(entry_id)\n assert data[\"rcsb_id\"] == \"14670951\"\n","repo_name":"erik-whiting/pdb_services","sub_path":"tests/data_api_tests/entry_service_test.py","file_name":"entry_service_test.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"14390498800","text":"import unittest\n\nimport unit_tests.test_cases.navigator_tests.NavigationTest as nav\nimport unit_tests.test_cases.collision_tests.tools_test as tools\nimport unit_tests.test_cases.direction_map_tests.DirectionMapTests as dm\n\nif __name__ == '__main__':\n # Run this file to run all unit test\n # Other python running methods aren't much more better in my opinion\n\n nav_1 = nav.TestAngle\n nav_2 = nav.TestDirection\n nav_3 = nav.TestDistance\n\n tool_1 = tools.ObstacleAdding\n tool_2 = tools.TestMarking\n\n directmap_1 = dm.GetingAngleTest\n directmap_2 = dm.GettingDirectionTests\n directmap_3 = dm.GettingPosTests\n directmap_4 = dm.GettingStepSizeTests\n\n\n unittest.main()\n","repo_name":"mblasiak/CrowdMovmentSimulation","sub_path":"unit_tests/run_all_tests.py","file_name":"run_all_tests.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"73568307777","text":"\"\"\"\nFaça um programa que pergunte a hora ao usuário e, baseando-se no horário\ndescrito, exiba a saudação apropriada. EX: Bom dia, Boa tarde, Boa noite.\n\"\"\"\n\nteclado = input('insira uma hora')\n\nif teclado.isdigit():\n teclado = float(teclado)\n\n if teclado < 0 or teclado > 23:\n print('Por favor insira um horario correto')\n\n else:\n if teclado <= 11:\n print('Bom dia')\n elif teclado <= 17:\n print('Boa tarde')\n else:\n print('Boa noite')\n\nelse:\n print('Por favor insira um horario correto')\n","repo_name":"Cristian-Nascimento/CursoPython","sub_path":"sessão-dois/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"21703043216","text":"import pytest\n\n\n@pytest.mark.parametrize('pp_type', [None, 'bfd', 'ccECP'])\n@pytest.mark.parametrize('name', ['LiH', 'C'])\nclass TestPhysics:\n def test_pseudo_potentials(self, helpers, name, pp_type, ndarrays_regression):\n mol = helpers.mol(name)\n hamil = helpers.hamil(mol, pp_type)\n phys_conf = helpers.phys_conf(hamil)\n _wf, params = helpers.create_ansatz(hamil)\n wf = lambda phys_conf: _wf.apply(params, phys_conf)\n ndarrays_regression.check(\n {\n 'local_potential': hamil.potential.local_potential(phys_conf),\n 'nonlocal_potential': (\n hamil.potential.nonloc_potential(helpers.rng(), phys_conf, wf)\n if pp_type\n else 0\n ),\n },\n default_tolerance={'rtol': 2e-2, 'atol': 1e-8},\n )\n # note: nonlocal_potential is not particularly\n # numerically stable, hence the large tolerance\n","repo_name":"deepqmc/deepqmc","sub_path":"tests/test_potential.py","file_name":"test_potential.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":308,"dataset":"github-code","pt":"80"} +{"seq_id":"20102859199","text":"# verification-helper: PROBLEM https://judge.yosupo.jp/problem/sort_points_by_argument\nimport sys\ninput = sys.stdin.buffer.readline\n\nfrom Geometry.atan2_sorted import atan2_sorted\n\n\ndef main():\n n = int(input())\n coords = [list(map(int, input().split())) for i in range(n)]\n\n ans = atan2_sorted(coords)\n for res in ans:\n print(*res)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Neterukun1993/Library","sub_path":"TestCase/LibraryChecker/sort_points_by_argument.test.py","file_name":"sort_points_by_argument.test.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"27612190569","text":"#!/usr/bin/python\n\n# https://leetcode.com/problems/shortest-word-distance/\n# Example\n# Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.\n#\n# Example:\n# Assume that words = [\"practice\", \"makes\", \"perfect\", \"coding\", \"makes\"].\n#\n# Input: word1 = “coding”, word2 = “practice”\n# Output: 3\n# Input: word1 = \"makes\", word2 = \"coding\"\n# Output: 1\n# Note:\n# You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.\n\"\"\"\nAlgo: Two pointers\nD.S.:\n\nSolution:\nTime: O(n) -- one pass\nSpace: O(1) -- two pointers\n\nCorner cases:\n\"\"\"\nclass Solution:\n def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:\n p1, p2 = None, None\n cur = 0\n res = len(words)\n while cur < len(words):\n if words[cur] == word1:\n p1 = cur\n if p2 != None:\n res = min(res, abs(p1 - p2))\n if words[cur] == word2:\n p2 = cur\n if p1 != None:\n res = min(res, abs(p1 - p2))\n cur += 1\n return res\n\n# Test Cases\nif __name__ == \"__main__\":\n solution = Solution()\n","repo_name":"JenZhen/LC","sub_path":"lc_ladder/Basic_Algo/two-pointers/Shortest_Words_Distance.py","file_name":"Shortest_Words_Distance.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71747581399","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Preview\nCode for 'Inf-Net: Automatic COVID-19 Lung Infection Segmentation from CT Scans'\nsubmit to Transactions on Medical Imaging, 2020.\n\nFirst Version: Created on 2020-05-13 (@author: Ge-Peng Ji)\n\"\"\"\n\nimport torch\nimport math\nimport time\nimport random\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.autograd import Variable\nimport torch.utils.data\nimport os\nimport numpy as np\nimport argparse\nfrom datetime import datetime\nfrom Code.utils.dataloader_LungInf import get_loader, COVIDDataset, IndicesDataset\nfrom Code.utils.utils import clip_gradient, adjust_lr, AvgMeter, timer\nimport torch.nn.functional as F\nfrom tensorboardX import SummaryWriter\nfrom sklearn.metrics import roc_curve, auc\nimport statistics\nimport matplotlib.pyplot as plt\nimport pickle\nfrom sklearn.model_selection import KFold\n\nfrom focal_loss import FocalLoss\nfrom lookahead import Lookahead\n\nimport sys\nsys.path.append('..')\n\nfrom InfNet.Code.utils.dataloader_LungInf import test_dataset\nfrom metric import dice_similarity_coefficient, jaccard_similarity_coefficient, sensitivity_similarity_coefficient, \\\n specificity_similarity_coefficient, precision_similarity_coefficient\n\nglobal_current_iteration = 0\nbest_loss = 1e9\nfocal_loss_criterion = FocalLoss(logits=True)\n\n\ndef joint_loss(pred, mask, opt):\n weit = 1 + 5*torch.abs(F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask)\n\n if opt.focal_loss:\n wbce = focal_loss_criterion(pred, mask)#, reduce='none')\n else:\n wbce = F.binary_cross_entropy_with_logits(pred, mask, reduce='none')\n wbce = (weit*wbce).sum(dim=(2, 3)) / weit.sum(dim=(2, 3))\n\n pred = torch.sigmoid(pred)\n inter = ((pred * mask)*weit).sum(dim=(2, 3))\n union = ((pred + mask)*weit).sum(dim=(2, 3))\n wiou = 1 - (inter + 1)/(union - inter+1)\n return (wbce + wiou).mean()\n\n\ndef train(train_loader, test_loader, model, optimizer, epoch, train_save, device, opt):\n global global_current_iteration\n global best_loss\n global focal_loss_criterion\n\n if opt.lookahead:\n optimizer = Lookahead(optimizer, k=5, alpha=0.5)\n optimizer.zero_grad()\n focal_loss_criterion = focal_loss_criterion.to(device)\n\n model.train()\n # ---- multi-scale training ----\n size_rates = [0.75, 1, 1.25] # replace your desired scale, try larger scale for better accuracy in small object\n loss_record1, loss_record2, loss_record3, loss_record4, loss_record5 = AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter()\n for i, pack in enumerate(train_loader, start=1):\n global_current_iteration += 1\n for rate in size_rates:\n optimizer.zero_grad()\n # ---- data prepare ----\n images, gts, edges = pack\n images = Variable(images).to(device)\n gts = Variable(gts).to(device)\n edges = Variable(edges).to(device)\n # ---- rescaling the inputs (img/gt/edge) ----\n trainsize = int(round(opt.trainsize*rate/32)*32)\n if rate != 1:\n images = F.upsample(images, size=(trainsize, trainsize), mode='bilinear', align_corners=True)\n gts = F.upsample(gts, size=(trainsize, trainsize), mode='bilinear', align_corners=True)\n edges = F.upsample(edges, size=(trainsize, trainsize), mode='bilinear', align_corners=True)\n\n # ---- forward ----\n lateral_map_5, lateral_map_4, lateral_map_3, lateral_map_2, lateral_edge = model(images)\n # ---- loss function ----\n loss5 = joint_loss(lateral_map_5, gts, opt)\n loss4 = joint_loss(lateral_map_4, gts, opt)\n loss3 = joint_loss(lateral_map_3, gts, opt)\n loss2 = joint_loss(lateral_map_2, gts, opt)\n loss1 = BCE(lateral_edge, edges)\n loss = loss1 + loss2 + loss3 + loss4 + loss5\n\n train_writer.add_scalar('train/edge_loss', loss1.item(), global_current_iteration)\n train_writer.add_scalar('train/loss2', loss2.item(), global_current_iteration)\n train_writer.add_scalar('train/loss3', loss3.item(), global_current_iteration)\n train_writer.add_scalar('train/loss4', loss4.item(), global_current_iteration)\n train_writer.add_scalar('train/loss5', loss5.item(), global_current_iteration)\n scalar_total_loss = loss2.item() + loss3.item() + loss4.item() + loss5.item()\n train_writer.add_scalar('train/total_loss', scalar_total_loss, global_current_iteration)\n\n # ---- backward ----\n loss.backward()\n clip_gradient(optimizer, opt.clip)\n optimizer.step()\n # ---- recording loss ----\n if rate == 1:\n loss_record1.update(loss1.data, opt.batchsize)\n loss_record2.update(loss2.data, opt.batchsize)\n loss_record3.update(loss3.data, opt.batchsize)\n loss_record4.update(loss4.data, opt.batchsize)\n loss_record5.update(loss5.data, opt.batchsize)\n # ---- train logging ----\n if i % 20 == 0 or i == total_step:\n print('{} Epoch [{:03d}/{:03d}], Step [{:04d}/{:04d}], [lateral-edge: {:.4f}, '\n 'lateral-2: {:.4f}, lateral-3: {:0.4f}, lateral-4: {:0.4f}, lateral-5: {:0.4f}]'.\n format(datetime.now(), epoch, opt.epoch, i, total_step, loss_record1.show(),\n loss_record2.show(), loss_record3.show(), loss_record4.show(), loss_record5.show()))\n # check testing error\n total_test_step = 0\n total_loss_5 = 0\n total_loss_4 = 0\n total_loss_3 = 0\n total_loss_2 = 0\n\n total_dice_5 = 0\n total_dice_4 = 0\n total_dice_3 = 0\n total_dice_2 = 0\n model.eval()\n for pack in test_loader:\n total_test_step += 1\n image, gt, _, name = pack\n image = Variable(image).to(device)\n gt = Variable(gt).to(device)\n # ---- forward ----\n lateral_map_5, lateral_map_4, lateral_map_3, lateral_map_2, lateral_edge = model(image)\n # ---- loss function ----\n loss5 = joint_loss(lateral_map_5, gt, opt)\n loss4 = joint_loss(lateral_map_4, gt, opt)\n loss3 = joint_loss(lateral_map_3, gt, opt)\n loss2 = joint_loss(lateral_map_2, gt, opt)\n total_loss_5 += loss5.item()\n total_loss_4 += loss4.item()\n total_loss_3 += loss3.item()\n total_loss_2 += loss2.item()\n\n total_dice_5 += dice_similarity_coefficient(lateral_map_5.sigmoid(), gt, 0.5)\n total_dice_4 += dice_similarity_coefficient(lateral_map_4.sigmoid(), gt, 0.5)\n total_dice_3 += dice_similarity_coefficient(lateral_map_3.sigmoid(), gt, 0.5)\n total_dice_2 += dice_similarity_coefficient(lateral_map_2.sigmoid(), gt, 0.5)\n\n total_average_loss = (total_loss_2 + total_loss_3 + total_loss_4 + total_loss_5) / total_test_step / 4\n test_writer.add_scalar('test/loss2', total_loss_2/total_test_step, global_current_iteration)\n test_writer.add_scalar('test/loss3', total_loss_3/total_test_step, global_current_iteration)\n test_writer.add_scalar('test/loss4', total_loss_4/total_test_step, global_current_iteration)\n test_writer.add_scalar('test/loss5', total_loss_5/total_test_step, global_current_iteration)\n test_writer.add_scalar('test/total_loss', total_average_loss, global_current_iteration)\n test_writer.add_scalar('test/dice', (total_dice_2 + total_dice_3 + total_dice_4 + total_dice_5) / total_test_step / 4, global_current_iteration)\n model.train()\n\n if total_average_loss < best_loss:\n best_loss = total_average_loss\n # ---- save model_lung_infection ----\n save_path = './Snapshots/save_weights/{}/'.format(train_save)\n os.makedirs(save_path, exist_ok=True)\n torch.save(model.state_dict(), save_path + 'Inf-Net-%d.pth' % (epoch + 1))\n print('[Saving Snapshot:]', save_path + 'Inf-Net-%d.pth' % (epoch + 1))\n return total_average_loss\n\n\ndef eval(test_loader, model, device, load_net_path, threshold, opt):\n total_test_step = 0\n total_loss_5 = []\n total_loss_4 = []\n total_loss_3 = []\n total_loss_2 = []\n\n total_dice_5 = []\n total_dice_4 = []\n total_dice_3 = []\n total_dice_2 = []\n\n total_jaccard_5 = []\n total_jaccard_4 = []\n total_jaccard_3 = []\n total_jaccard_2 = []\n\n total_sens_5 = []\n total_sens_4 = []\n total_sens_3 = []\n total_sens_2 = []\n\n total_spec_5 = []\n total_spec_4 = []\n total_spec_3 = []\n total_spec_2 = []\n\n total_precision_2 = []\n\n total_auc_2 = []\n\n roc_2 = []\n ground_truth_list = []\n\n model.eval()\n for pack in test_loader:\n total_test_step += 1\n image, gt_cont, gt_roc, name = pack\n image = Variable(image).to(device)\n gt_cont = Variable(gt_cont).to(device)\n gt_roc = Variable(gt_roc).to(device)\n # ---- forward ----\n lateral_map_5, lateral_map_4, lateral_map_3, lateral_map_2, lateral_edge = model(image)\n # ---- loss function ----\n # loss5 = joint_loss(lateral_map_5, gt)\n # loss4 = joint_loss(lateral_map_4, gt)\n # loss3 = joint_loss(lateral_map_3, gt)\n # loss2 = joint_loss(lateral_map_2, gt)\n # loss5 = torch.mean(torch.abs(lateral_map_5 - gt_cont))\n # loss4 = torch.mean(torch.abs(lateral_map_4 - gt_cont))\n # loss3 = torch.mean(torch.abs(lateral_map_3 - gt_cont))\n loss2 = torch.mean(torch.abs(lateral_map_2 - gt_cont))\n # total_loss_5.append(loss5.item())\n # total_loss_4.append(loss4.item())\n # total_loss_3.append(loss3.item())\n total_loss_2.append(loss2.item())\n\n # total_dice_5.append(dice_similarity_coefficient(lateral_map_5.sigmoid(), gt_cont))\n # total_dice_4.append(dice_similarity_coefficient(lateral_map_4.sigmoid(), gt_cont))\n # total_dice_3.append(dice_similarity_coefficient(lateral_map_3.sigmoid(), gt_cont))\n current_dice = dice_similarity_coefficient(lateral_map_2.sigmoid(), gt_roc, threshold)\n if not math.isnan(current_dice):\n total_dice_2.append(current_dice)\n\n # total_jaccard_5.append(jaccard_similarity_coefficient(lateral_map_5.sigmoid(), gt_cont))\n # total_jaccard_4.append(jaccard_similarity_coefficient(lateral_map_4.sigmoid(), gt_cont))\n # total_jaccard_3.append(jaccard_similarity_coefficient(lateral_map_3.sigmoid(), gt_cont))\n current_jaccard = jaccard_similarity_coefficient(lateral_map_2.sigmoid(), gt_roc, threshold)\n if not math.isnan(current_jaccard):\n total_jaccard_2.append(current_jaccard)\n\n roc_2 += lateral_map_2.sigmoid().detach().view(-1).cpu().numpy().tolist()\n ground_truth_list += gt_roc.detach().view(-1).cpu().numpy().tolist()\n\n # total_sens_5.append(sensitivity_similarity_coefficient(lateral_map_5.sigmoid(), gt_roc, threshold))\n # total_sens_4.append(sensitivity_similarity_coefficient(lateral_map_4.sigmoid(), gt_roc, threshold))\n # total_sens_3.append(sensitivity_similarity_coefficient(lateral_map_3.sigmoid(), gt_roc, threshold))\n current_sens = sensitivity_similarity_coefficient(lateral_map_2.sigmoid(), gt_roc, threshold)\n if not math.isnan(current_sens):\n total_sens_2.append(current_sens)\n\n # total_spec_5.append(specificity_similarity_coefficient(lateral_map_5.sigmoid(), gt_roc, threshold))\n # total_spec_4.append(specificity_similarity_coefficient(lateral_map_4.sigmoid(), gt_roc, threshold))\n # total_spec_3.append(specificity_similarity_coefficient(lateral_map_3.sigmoid(), gt_roc, threshold))\n current_precision = precision_similarity_coefficient(lateral_map_2.sigmoid(), gt_roc, threshold)\n if not math.isnan(current_precision):\n total_precision_2.append(current_precision)\n\n fpr, tpr, thresholds = roc_curve(gt_roc.view(-1).detach().cpu().numpy(),\n lateral_map_2.sigmoid().view(-1).detach().cpu().numpy())\n roc_auc_2 = auc(fpr, tpr)\n if not math.isnan(roc_auc_2):\n total_auc_2.append(roc_auc_2)\n\n fpr, tpr, thresholds = roc_curve(ground_truth_list, roc_2)\n\n roc_auc = auc(fpr, tpr)\n print(f'auc: {roc_auc}')\n # get threshold cutoff\n optimal_idx = np.argmax(tpr - fpr)\n optimal_threshold = thresholds[optimal_idx]\n optimal_fpr = fpr[optimal_idx]\n optimal_tpr = tpr[optimal_idx]\n print(f'optimal threshold: {optimal_threshold} , tpr: {tpr[optimal_idx]}, fpr: {fpr[optimal_idx]}')\n\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.plot(optimal_fpr, optimal_tpr, 'go')\n plt.annotate(f'{optimal_threshold}', (optimal_fpr, optimal_tpr))\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 if load_net_path is not None:\n title = load_net_path.split(os.sep)[-2]\n else:\n title = opt.train_save\n plt.title(f'{title}')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n roc_dict = {'tpr': tpr, 'fpr': fpr, 'optimal_tpr': optimal_tpr, 'optimal_fpr': optimal_fpr,\n 'optimal_threshold': optimal_threshold}\n save_roc_dict_dir = './roc_saves'\n os.makedirs(save_roc_dict_dir, exist_ok=True)\n save_roc_dict_filename = os.path.join(save_roc_dict_dir, title)\n with open(save_roc_dict_filename, 'wb') as f:\n pickle.dump(roc_dict, f, pickle.HIGHEST_PROTOCOL)\n\n # accumulated_loss = (np.array(total_loss_2) + np.array(total_loss_3) + np.array(total_loss_4) + np.array(\n # total_loss_5)) / 4\n accumulated_loss = np.array(total_loss_2)\n mean_loss = np.mean(accumulated_loss)\n error_loss = np.std(accumulated_loss) / np.sqrt(accumulated_loss.size) * 1.96\n\n # accumulated_dice = (np.array(total_dice_2) + np.array(total_dice_3) + np.array(total_dice_4) + np.array(\n # total_dice_5)) / 4\n accumulated_dice = np.array(total_dice_2)\n mean_dice = np.mean(accumulated_dice)\n error_dice = np.std(accumulated_dice) / np.sqrt(accumulated_dice.size) * 1.96\n\n # accumulated_jaccard = (np.array(total_jaccard_2) + np.array(total_jaccard_3) + np.array(total_jaccard_4) + np.array(\n # total_jaccard_5)) / 4\n accumulated_jaccard = np.array(total_jaccard_2)\n mean_jaccard = np.mean(accumulated_jaccard)\n error_jaccard = np.std(accumulated_jaccard) / np.sqrt(accumulated_jaccard.size) * 1.96\n\n # accumulated_sens = (np.array(total_sens_2) + np.array(total_sens_3) + np.array(total_sens_4) + np.array(\n # total_sens_5)) / 4\n accumulated_sens = np.array(total_sens_2)\n mean_sens = np.mean(accumulated_sens)\n error_sens = np.std(accumulated_sens) / np.sqrt(accumulated_sens.size) * 1.96\n\n # accumulated_spec = (np.array(total_spec_2) + np.array(total_spec_3) + np.array(total_spec_4) + np.array(\n # total_spec_5)) / 4\n accumulated_precision = np.array(total_precision_2)\n mean_precision = np.mean(accumulated_precision)\n error_precision = np.std(accumulated_precision) / np.sqrt(accumulated_precision.size) * 1.96\n\n accumulated_auc = np.array(total_auc_2)\n mean_auc = np.mean(accumulated_auc)\n error_auc = np.std(accumulated_auc) / np.sqrt(accumulated_auc.size) * 1.96\n\n with open('single_metric.txt', 'a') as f:\n f.write(title + '\\n')\n for loss in accumulated_dice:\n f.write(str(loss) + '\\n')\n\n metric_string = \"\"\n metric_string += f'mean absolute loss: {mean_loss}\\n'\n metric_string += f'error absolute loss: {error_loss}\\n'\n metric_string += '=============================\\n'\n metric_string += f'mean dice: {mean_dice}\\n'\n metric_string += f'error dice: {error_dice}\\n'\n metric_string += '=============================\\n'\n metric_string += f'mean jaccard: {mean_jaccard}\\n'\n metric_string += f'error jaccard: {error_jaccard}\\n'\n metric_string += '=============================\\n'\n metric_string += f'mean sens: {mean_sens}\\n'\n metric_string += f'error sens: {error_sens}\\n'\n metric_string += '=============================\\n'\n metric_string += f'mean precision: {mean_precision}\\n'\n metric_string += f'error precision: {error_precision}\\n'\n metric_string += '=============================\\n'\n metric_string += f'mean auc: {mean_auc}\\n'\n metric_string += f'error auc: {error_auc}\\n'\n\n return metric_string\n\n\ndef cross_validation(train_save, opt):\n image_root = '{}/Imgs/'.format(opt.all_path)\n gt_root = '{}/GT/'.format(opt.all_path)\n edge_root = '{}/Edge/'.format(opt.all_path)\n\n images = np.array(sorted([image_root + f for f in os.listdir(image_root) if f.endswith('.jpg') or f.endswith('.png')]))\n gts = np.array(sorted([gt_root + f for f in os.listdir(gt_root) if f.endswith('.png')]))\n edges = np.array(sorted([edge_root + f for f in os.listdir(edge_root) if f.endswith('.png')]))\n\n k_folds = KFold(opt.folds)\n VALIDATION_EARLY_STOPPING = 6\n for fold_index, (train_index, test_index) in enumerate(k_folds.split(images)):\n best_loss = 99999\n current_validation_early_count = 0\n random.seed(opt.seed)\n np.random.seed(opt.seed)\n torch.manual_seed(opt.seed)\n torch.cuda.manual_seed(opt.seed)\n torch.random.manual_seed(opt.seed)\n model, optimizer = create_model(opt)\n\n train_dataset = IndicesDataset(images[train_index], gts[train_index], edges[train_index], opt.trainsize, opt.is_data_augment, opt.random_cutout)\n test_dataset = IndicesDataset(images[test_index], gts[test_index], None, opt.trainsize, opt.is_data_augment, opt.random_cutout, is_test=True)\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=opt.batchsize,\n shuffle=True,\n num_workers=opt.num_workers,\n pin_memory=True,\n drop_last=False)\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=opt.batchsize,\n shuffle=True,\n num_workers=opt.num_workers,\n pin_memory=True,\n drop_last=False)\n\n for epoch in range(1, opt.epoch):\n adjust_lr(optimizer, opt.lr, epoch, opt.decay_rate, opt.decay_epoch)\n average_test_loss = train(train_loader, test_loader, model, optimizer, epoch, train_save, opt.device, opt)\n if average_test_loss < best_loss:\n best_loss = average_test_loss\n current_validation_early_count = 0\n else:\n current_validation_early_count += 1\n if current_validation_early_count >= VALIDATION_EARLY_STOPPING:\n break\n metric_string = eval(test_loader, model, opt.device, None, opt.eval_threshold, opt)\n\n # write the metrics\n os.makedirs(os.path.join(opt.metric_path, opt.train_save), exist_ok=True)\n filename = os.path.join(opt.metric_path, opt.train_save, f\"metrics_{fold_index}.txt\")\n with open(f'{filename}', 'a') as f:\n f.write(metric_string)\n\n\ndef create_model(opt):\n model = Inf_Net(channel=opt.net_channel, n_class=opt.n_classes).to(opt.device)\n params = model.parameters()\n optimizer = torch.optim.Adam(params, opt.lr)\n return model, optimizer\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # hyper-parameters\n parser.add_argument('--folds', type=int, default=0)\n parser.add_argument('--epoch', type=int, default=100,\n help='epoch number')\n parser.add_argument('--seed', type=int, default=100)\n parser.add_argument('--lr', type=float, default=1e-4,\n help='learning rate')\n parser.add_argument('--batchsize', type=int, default=24,\n help='training batch size')\n parser.add_argument('--trainsize', type=int, default=352,\n help='set the size of training sample')\n parser.add_argument('--clip', type=float, default=0.5,\n help='gradient clipping margin')\n parser.add_argument('--decay_rate', type=float, default=0.1,\n help='decay rate of learning rate')\n parser.add_argument('--decay_epoch', type=int, default=50,\n help='every n epochs decay learning rate')\n parser.add_argument('--is_thop', type=bool, default=True,\n help='whether calculate FLOPs/Params (Thop)')\n parser.add_argument('--gpu_device', type=int, default=0,\n help='choose which GPU device you want to use')\n parser.add_argument('--num_workers', type=int, default=0,\n help='number of workers in dataloader. In windows, set num_workers=0')\n parser.add_argument('--device', type=str, default='cpu')\n # model_lung_infection parameters\n parser.add_argument('--net_channel', type=int, default=32,\n help='internal channel numbers in the Inf-Net, default=32, try larger for better accuracy')\n parser.add_argument('--n_classes', type=int, default=1,\n help='binary segmentation when n_classes=1')\n parser.add_argument('--backbone', type=str, default='ResNet50',\n help='change different backbone, choice: VGGNet16, ResNet50, Res2Net50')\n # training dataset\n parser.add_argument('--train_path', type=str,\n default='./Dataset/TrainingSet/LungInfection-Train/Doctor-label')\n parser.add_argument('--is_semi', type=bool, default=False,\n help='if True, you will turn on the mode of `Semi-Inf-Net`')\n parser.add_argument('--is_pseudo', type=bool, default=False,\n help='if True, you will train the model on pseudo-label')\n parser.add_argument('--train_save', type=str, default=None,\n help='If you use custom save path, please edit `--is_semi=True` and `--is_pseudo=True`')\n parser.add_argument('--is_data_augment', type=bool, default=False)\n parser.add_argument('--random_cutout', type=float, default=0)\n\n # testing dataset\n parser.add_argument('--test_path', type=str, default=\"./Dataset/TestingSet/LungInfection-Test/\")\n parser.add_argument('--val_path', type=str, default=\"./Dataset/ValSet/LungInfection-Val\")\n parser.add_argument('--all_path', type=str, default=\"./Dataset/AllSet/LungInfection-All\")\n parser.add_argument('--testsize', type=int, default=352, help='testing size')\n parser.add_argument('--valsize', type=int, default=352, help='validation size')\n\n\n # load model path\n parser.add_argument('--load_net_path', type=str)\n\n # new techniques\n parser.add_argument('--focal_loss', action='store_true')\n parser.add_argument('--lookahead', action='store_true')\n\n # save log tensorboard\n parser.add_argument('--graph_path', type=str, default=\"./graph_log\")\n parser.add_argument('--is_eval', type=bool, default=False)\n parser.add_argument('--metric_path', type=str, default='./metrics_log')\n parser.add_argument('--eval_threshold', type=float, help='Use for threshold the sigmoid to get 1 or 0')\n\n opt = parser.parse_args()\n\n # ---- build models ----\n # torch.cuda.set_device(opt.gpu_device)\n\n if opt.backbone == 'Res2Net50':\n print('Backbone loading: Res2Net50')\n from Code.model_lung_infection.InfNet_Res2Net import Inf_Net\n elif opt.backbone == 'ResNet50':\n print('Backbone loading: ResNet50')\n from Code.model_lung_infection.InfNet_ResNet import Inf_Net\n elif opt.backbone == 'VGGNet16':\n print('Backbone loading: VGGNet16')\n from Code.model_lung_infection.InfNet_VGGNet import Inf_Net\n else:\n raise ValueError('Invalid backbone parameters: {}'.format(opt.backbone))\n\n random.seed(opt.seed)\n np.random.seed(opt.seed)\n torch.manual_seed(opt.seed)\n torch.cuda.manual_seed(opt.seed)\n torch.random.manual_seed(opt.seed)\n model, optimizer = create_model(opt)\n\n if opt.load_net_path:\n net_state_dict = torch.load(opt.load_net_path, map_location=torch.device(opt.device))\n net_state_dict = {k: v for k, v in net_state_dict.items() if k in model.state_dict()}\n model.load_state_dict(net_state_dict)\n\n # ---- load pre-trained weights (mode=Semi-Inf-Net) ----\n # - See Sec.2.3 of `README.md` to learn how to generate your own img/pseudo-label from scratch.\n if opt.is_semi and opt.backbone == 'Res2Net50':\n print('Loading weights from weights file trained on pseudo label')\n model.load_state_dict(torch.load('./Snapshots/save_weights/Inf-Net_Pseduo/Inf-Net_pseudo_100.pth'))\n else:\n print('Not loading weights from weights file')\n\n # weights file save path\n if opt.is_pseudo and (not opt.is_semi):\n train_save = 'Inf-Net_Pseudo'\n elif (not opt.is_pseudo) and opt.is_semi:\n train_save = 'Semi-Inf-Net'\n elif (not opt.is_pseudo) and (not opt.is_semi):\n train_save = 'Inf-Net'\n else:\n print('Use custom save path')\n train_save = opt.train_save\n train_save = opt.train_save\n\n # ---- calculate FLOPs and Params ----\n if opt.is_thop:\n from Code.utils.utils import CalParams\n x = torch.randn(1, 3, opt.trainsize, opt.trainsize).to(opt.device)\n CalParams(model, x)\n\n # ---- load training sub-modules ----\n BCE = torch.nn.BCEWithLogitsLoss()\n\n train_writer = SummaryWriter(logdir=os.path.join(opt.graph_path, 'training'))\n test_writer = SummaryWriter(logdir=os.path.join(opt.graph_path, 'testing'))\n\n image_root = '{}/Imgs/'.format(opt.train_path)\n gt_root = '{}/GT/'.format(opt.train_path)\n edge_root = '{}/Edge/'.format(opt.train_path)\n\n train_loader = get_loader(image_root, gt_root, edge_root,\n batchsize=opt.batchsize, trainsize=opt.trainsize, num_workers=opt.num_workers,\n is_data_augment=opt.is_data_augment, random_cutout=opt.random_cutout)\n\n test_image_root = '{}/Imgs/'.format(opt.test_path)\n test_gt_root = '{}/GT/'.format(opt.test_path)\n test_data = test_dataset(test_image_root, test_gt_root, opt.testsize)\n test_loader = DataLoader(test_data, batch_size=opt.batchsize, num_workers=opt.num_workers)\n\n val_image_root = '{}/Imgs/'.format(opt.val_path)\n val_gt_root = '{}/GT/'.format(opt.val_path)\n val_data = test_dataset(val_image_root, val_gt_root, opt.valsize)\n val_loader = DataLoader(val_data, batch_size=opt.batchsize, num_workers=opt.num_workers)\n\n total_step = len(train_loader)\n\n # ---- start !! -----\n print(\"#\"*20, \"\\nStart Training (Inf-Net-{})\\n{}\\nThis code is written for 'Inf-Net: Automatic COVID-19 Lung \"\n \"Infection Segmentation from CT Scans', 2020, arXiv.\\n\"\n \"----\\nPlease cite the paper if you use this code and dataset. \"\n \"And any questions feel free to contact me \"\n \"via E-mail (gepengai.ji@163.com)\\n----\\n\".format(opt.backbone, opt), \"#\"*20)\n\n if opt.is_eval:\n start = time.time()\n metric_string = eval(test_loader, model, opt.device, opt.load_net_path, opt.eval_threshold, opt)\n end = time.time()\n timer(start, end)\n print(metric_string)\n # write the metrics\n os.makedirs(os.path.join(opt.metric_path, opt.load_net_path), exist_ok=True)\n with open(f'{os.path.join(opt.metric_path, opt.load_net_path, \"metrics.txt\")}', 'a') as f:\n f.write(metric_string)\n else:\n\n if opt.folds == 0:\n for epoch in range(1, opt.epoch):\n start = time.time()\n adjust_lr(optimizer, opt.lr, epoch, opt.decay_rate, opt.decay_epoch)\n train(train_loader, val_loader, model, optimizer, epoch, train_save, opt.device, opt)\n end = time.time()\n timer(start, end)\n else:\n del train_loader, val_loader\n cross_validation(train_save, opt)\n\n","repo_name":"darylfung96/self-supervised-CT-segmentation","sub_path":"InfNet/MyTrain_LungInf.py","file_name":"MyTrain_LungInf.py","file_ext":"py","file_size_in_byte":28422,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"34016034162","text":"#Another Brick in the Wall\r\n\r\n#taking in the input\r\ndimensions = [int(s) for s in input().split()]\r\nbricks = [int(s) for s in input().split()]\r\n#breaking up the input into variables\r\nheight, width, iterations = dimensions[0], dimensions[1], dimensions[2]\r\n\r\n#completed counts progress of row as it builds\r\ncompleted = 0\r\n#layers counts progress of layers as they build\r\nlayers = 0\r\nbroken = True\r\n\r\nfor i in range(iterations):\r\n if layers == height:\r\n layers += 1\r\n break\r\n else:\r\n completed += bricks[i]\r\n if completed > width:\r\n broken = True\r\n break\r\n if completed == width:\r\n layers += 1\r\n completed = 0\r\n\r\nif layers < height and broken:\r\n print(\"NO\")\r\nelse:\r\n print(\"YES\")\r\n","repo_name":"DMamrenko/Kattis-Problems","sub_path":"another_brick_in_the_wall.py","file_name":"another_brick_in_the_wall.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"14794784251","text":"import discord\r\nimport asyncio\r\nimport json\r\nfrom discord.utils import get\r\n\r\nasync def ex(args, message, client, invoke):\r\n\r\n user = message.author.id\r\n mentions = message.mentions\r\n\r\n name_list = [\"\"]\r\n for i in range (0,len(args)):\r\n name_list.append(args[i])\r\n name_list = \" \".join(name_list)\r\n\r\n name = name_list.strip()\r\n if len(name) > 0:\r\n\r\n async def update_data(teams, name):\r\n exists = False\r\n team_role_exists = False\r\n team_role_needed = str(name)\r\n\r\n for t_name, t_info in teams.items():\r\n for key in t_info:\r\n if t_info[key] == user:\r\n exists = True\r\n\r\n if not name in teams and exists == False:\r\n teams[name] = {}\r\n teams[name]['captain'] = user\r\n teams[name]['member1'] = \"placeholder\"\r\n teams[name]['member2'] = \"placeholder\"\r\n teams[name]['member3'] = \"placeholder\"\r\n\r\n author = message.author\r\n\r\n cap_role = get(author.server.roles, name=\"Captain\")\r\n await client.add_roles(author, cap_role)\r\n\r\n if team_role_needed.lower() in [y.name.lower() for y in author.server.roles]:\r\n team_role_exists = True\r\n\r\n if team_role_exists == False:\r\n await client.create_role(author.server, name=name)\r\n\r\n team_role = get(author.server.roles, name=name)\r\n await client.add_roles(author, team_role)\r\n\r\n await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.green(), description=\"Team created\"))\r\n\r\n elif exists == True:\r\n await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.green(), description=\"You are already in a team.\"))\r\n\r\n else:\r\n await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.red(), description=\"Team already exists\"))\r\n\r\n with open(\"data/teams.json\", \"r\") as f:\r\n teams = json.load(f)\r\n\r\n await update_data(teams, name)\r\n\r\n with open(\"data/teams.json\", \"w\") as f:\r\n json.dump(teams, f, indent=4)\r\n\r\n else:\r\n await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.red(), description=\"This command should be formatted **~team-create {TEAM NAME}**\"))\r\n","repo_name":"HaaZee/discordbot","sub_path":"commands/cmd_team_create.py","file_name":"cmd_team_create.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"22515689497","text":"import json\nimport shutil\nimport tempfile\nimport unittest\nfrom os import path\n\nfrom src.graphworks.export.graphviz_utils import save_to_dot\nfrom src.graphworks.export.json_utils import save_to_json\nfrom src.graphworks.graph import Graph\n\n\nclass ExportTests(unittest.TestCase):\n def setUp(self):\n # Create a temporary directory\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n # Remove the directory after the test\n shutil.rmtree(self.test_dir)\n\n def test_save_to_json(self):\n answer = \"{\\\"label\\\": \\\"my graph\\\", \\\"directed\\\": false,\" \\\n \" \\\"graph\\\": {\\\"A\\\": [\\\"B\\\"], \\\"B\\\": []}}\"\n json_graph = {\"label\": \"my graph\", \"graph\": {\"A\": [\"B\"], \"B\": []}}\n graph = Graph(input_graph=json.dumps(json_graph))\n save_to_json(graph, self.test_dir)\n\n outfile = path.join(self.test_dir, graph.get_label() + \".json\")\n with open(outfile) as dot_file:\n dot_lines = \"\".join(dot_file.readlines())\n self.assertEqual(dot_lines, answer)\n\n def test_save_to_graphviz(self):\n answer = \"\"\"// my graph\ngraph {\n\tA [label=A]\n\tA -- B\n\tB [label=B]\n}\n\"\"\"\n json_graph = {\"label\": \"my graph\", \"graph\": {\"A\": [\"B\"], \"B\": []}}\n graph = Graph(input_graph=json.dumps(json_graph))\n save_to_dot(graph, self.test_dir)\n\n outfile = path.join(self.test_dir, graph.get_label() + \".gv\")\n with open(outfile) as dot_file:\n dot_lines = \"\".join(dot_file.readlines())\n self.assertEqual(dot_lines, answer)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"nathan-gilbert/graphworks","sub_path":"tests/export_tests.py","file_name":"export_tests.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"37261914495","text":"\"\"\"\nModule containing all database definitions\n\"\"\"\nimport collections\nimport json\n\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\nfrom dtf.validators import JSONSchemaValidator\n\nclass Membership(models.Model):\n user = models.ForeignKey(\n User,\n null=False,\n blank=False,\n related_name=\"memberships\",\n on_delete=models.CASCADE,\n )\n\n project = models.ForeignKey(\n \"Project\",\n null=False,\n blank=False,\n related_name=\"memberships\",\n on_delete=models.CASCADE,\n )\n\n AVAILABLE_ROLES = [\n (\"owner\", \"Owner\"),\n (\"developer\", \"Developer\"),\n (\"guest\", \"Guest\")\n ]\n role = models.CharField(choices=AVAILABLE_ROLES, default=\"guest\", max_length=20)\n\n required_project_membership_role = {\n 'view' : 'guest',\n 'add' : 'owner',\n 'change' : 'owner',\n 'delete' : 'owner'\n }\n\n class Meta:\n unique_together = (\"user\", \"project\")\n\nclass Project(models.Model):\n \"\"\"\n Very simple project model\n\n Just stores the name of the project to be referenced in submitted test results\n \"\"\"\n name = models.CharField(max_length=100, blank=False)\n slug = models.SlugField(max_length=40, blank=False, unique=True)\n\n created = models.DateTimeField(default=timezone.now, editable=False, blank=True)\n last_updated = models.DateTimeField(auto_now=True)\n\n members = models.ManyToManyField(User, related_name=\"projects\", through=Membership, through_fields=(\"project\", \"user\"))\n\n required_project_membership_role = {\n 'view' : 'guest',\n 'change' : 'owner',\n 'delete' : 'owner'\n }\n\n def get_nav_data(self, test_name, submission_id):\n nav_data = {\n \"previous\": {\n \"exists\": False\n },\n \"next\": {\n \"exists\": False\n },\n \"most_recent\": {\n }\n }\n \n same_project_tests = TestResult.objects.filter(\n name=test_name,\n submission__project__id=self.id\n ).order_by(\"id\")\n\n # previous test\n previous_test = same_project_tests.filter(\n submission__id__lt=submission_id\n ).order_by(\"-id\").first()\n \n if previous_test:\n nav_data[\"previous\"][\"exists\"] = True\n nav_data[\"previous\"][\"id\"] = previous_test.id\n\n # next test\n next_test = same_project_tests.filter(\n submission__id__gt=submission_id\n ).order_by(\"id\").first()\n\n if next_test:\n nav_data[\"next\"][\"exists\"] = True\n nav_data[\"next\"][\"id\"] = next_test.id\n\n # most recent\n most_recent_test = same_project_tests.order_by(\"-submission__id\").first()\n nav_data[\"most_recent\"][\"id\"] = most_recent_test.id\n return nav_data\n\n def __str__(self):\n return f\"{self.name} [id = {self.id}]\"\n\n class Meta:\n app_label = 'dtf'\n\nclass ProjectSubmissionProperty(models.Model):\n project = models.ForeignKey(Project, on_delete=models.CASCADE, null=False, related_name=\"properties\")\n\n name = models.CharField(max_length=100, blank=False)\n required = models.BooleanField(default=False)\n display = models.BooleanField(default=True)\n display_replace = models.CharField(max_length=100, blank=True)\n display_as_link = models.BooleanField(default=False)\n influence_reference = models.BooleanField(default=False)\n\n required_project_membership_role = {\n 'view' : 'developer',\n 'add' : 'owner',\n 'change' : 'owner',\n 'delete' : 'owner'\n }\n\n class Meta:\n app_label = 'dtf'\n constraints = [\n models.UniqueConstraint(\n fields=['project', 'name'], \n name='unique_submission_property'\n )\n ]\n\nclass Submission(models.Model):\n \"\"\"\n Test results get grouped in submissions.\n\n Basically a submission is a run of a whole test suite. Every test and parameter of that suit gets assigned to this submission\n \"\"\"\n _info_json_schema = {\n 'schema': 'http://json-schema.org/draft-07/schema#',\n 'type': 'object',\n \"additionalProperties\": { \"type\": \"string\" }\n }\n\n project = models.ForeignKey(Project, on_delete=models.CASCADE, null=False, related_name=\"submissions\")\n created = models.DateTimeField(default=timezone.now, editable=False, blank=True)\n last_updated = models.DateTimeField(auto_now=True)\n info = models.JSONField(null=False, default=dict, validators=[JSONSchemaValidator(schema=_info_json_schema)])\n\n required_project_membership_role = {\n 'view' : 'guest',\n 'add' : 'owner',\n 'change' : 'owner',\n 'delete' : 'owner'\n }\n\n def status(self):\n status = None\n for test in self.tests.all():\n test_status = test.status\n if status is None or TestResult.status_order[test_status] > TestResult.status_order[status]:\n status = test_status\n if status is None:\n return \"unknown\"\n return status\n\n class Meta:\n app_label = 'dtf'\n\nclass TestResult(models.Model):\n \"\"\"\n Model to store test results and metadata\n \"\"\"\n _value_json_schema = {\n 'type': 'object',\n 'properties': {\n 'data': {},\n 'type': {\n 'type': 'string',\n 'enum': [\n 'integer',\n 'float',\n 'string',\n 'duration',\n 'ndarray',\n 'image'\n ]\n },\n },\n 'allOf': [\n {\n 'if': {\n 'properties': {'type': {'const': 'integer'}}\n },\n 'then': {\n 'properties': {'data': {'type': 'integer'}}\n }\n },\n {\n 'if': {\n 'properties': {'type': {'const': 'float'}}\n },\n 'then': {\n 'properties': {'data': {'type': 'number'}}\n }\n },\n {\n 'if': {\n 'properties': {'type': {'const': 'string'}}\n },\n 'then': {\n 'properties': {'data': {'type': 'string'}}\n }\n },\n {\n 'if': {\n 'properties': {'type': {'const': 'duration'}}\n },\n 'then': {\n 'properties': {\n 'data': {\n 'type': 'string',\n # ISO 8601 duration\n 'pattern': R'^(?P[-+]?)P(?:(?P\\d+(\\.\\d+)?)D)?(?:T(?:(?P\\d+(\\.\\d+)?)H)?(?:(?P\\d+(\\.\\d+)?)M)?(?:(?P\\d+(\\.\\d+)?)S)?)?$'\n }\n }\n }\n },\n {\n 'if': {\n 'properties': {'type': {'const': 'ndarray'}}\n },\n 'then': {\n 'properties': {'data': {\n 'type': 'object',\n 'properties': {\n 'shape': {\n 'type': 'array',\n 'items': {'type': 'integer'}\n },\n 'entries': {\n 'type': 'array',\n 'items': {'$ref': '#/definitions/value'}\n }\n },\n 'required': ['shape', 'entries'],\n 'additionalProperties': False\n }}\n }\n },\n {\n 'if': {\n 'properties': {'type': {'const': 'image'}}\n },\n 'then': {\n 'properties': {'data': {'type': 'string',\n 'contentEncoding': 'base64',\n 'contentMediaType': 'image/png'}}\n }\n },\n ],\n 'required': ['data', 'type'],\n 'additionalProperties': False\n }\n\n _results_json_schema = {\n 'schema': 'http://json-schema.org/draft-07/schema#',\n 'definitions': {\n 'value': _value_json_schema\n },\n 'type': 'array',\n 'items': {\n 'type': 'object',\n 'properties': {\n 'name': {\n 'type': 'string'\n },\n 'value': {\n 'oneOf': [\n {'$ref': '#/definitions/value'},\n {'type': 'null'}\n ]\n },\n 'reference': {\n 'oneOf': [\n {'$ref': '#/definitions/value'},\n {'type': 'null'}\n ]\n },\n 'reference_source': {'type': 'integer'},\n 'status': {\n 'type': 'string',\n 'enum': [\n 'skip',\n 'successful',\n 'unstable',\n 'unknown',\n 'failed',\n 'broken'\n ],\n 'default': 'unknown'\n }\n },\n 'additionalProperties': False,\n 'required': ['name', 'value']\n }\n }\n\n name = models.CharField(max_length=100, blank=False, db_index=True)\n submission = models.ForeignKey(Submission, on_delete=models.CASCADE, null=False, related_name=\"tests\")\n created = models.DateTimeField(default=timezone.now, editable=False, blank=True)\n last_updated = models.DateTimeField(auto_now=True)\n results = models.JSONField(null=True, validators=[JSONSchemaValidator(schema=_results_json_schema)])\n\n POSSIBLE_STATUS = [\n (\"skip\", \"skip\"),\n (\"successful\", \"successful\"),\n (\"unstable\", \"unstable\"),\n (\"unknown\", \"unknown\"),\n (\"failed\", \"failed\"),\n (\"broken\", \"broken\")\n ]\n\n status = models.CharField(choices=POSSIBLE_STATUS, default=\"unknown\", max_length=20)\n\n status_order = {\n \"skip\": 0,\n \"successful\": 1,\n \"unknown\": 2,\n \"unstable\": 3,\n \"failed\": 4,\n \"broken\": 5\n }\n\n required_project_membership_role = {\n 'view' : 'guest',\n 'add' : 'developer',\n 'change' : 'developer',\n 'delete' : 'owner'\n }\n\n def calculate_status(self):\n status = None\n for result in self.results:\n if status is None or self.status_order[result['status']] > self.status_order[status]:\n status = result['status']\n if status is None:\n self.status = \"unknown\"\n else:\n self.status = status\n\n def save(self, *args, **kwargs):\n self.calculate_status()\n super(TestResult, self).save(*args, **kwargs)\n\n def get_next_not_successful_test_id(self):\n same_submission_tests = self.submission.tests.all()\n not_successful = same_submission_tests.filter(\n created__gt=self.created\n ).exclude(status = \"successful\").order_by(\"created\").values(\"id\").first()\n \n if not_successful:\n return not_successful[\"id\"]\n return None\n\n def __str__(self):\n if self.submission:\n return f\"{self.name} [{self.submission.pk}]\"\n return f\"{self.name} [None]\"\n\n class Meta:\n app_label = 'dtf'\n\n\nclass ReferenceSet(models.Model):\n\n _properties_json_schema = {\n 'schema': 'http://json-schema.org/draft-07/schema#',\n 'type': 'object',\n \"additionalProperties\": { \"type\": \"string\" }\n }\n\n project = models.ForeignKey(Project, on_delete=models.CASCADE, null=False, related_name=\"reference_sets\")\n\n created = models.DateTimeField(default=timezone.now, editable=False, blank=True)\n last_updated = models.DateTimeField(auto_now=True)\n\n required_project_membership_role = {\n 'view' : 'guest',\n 'add' : 'developer',\n 'change' : 'developer',\n 'delete' : 'owner'\n }\n\n # We do use a special JSON decoder, that creates `OrderedDict` instead of `dict`\n # objects. This will allow us to sort the properties by their keys, so that the\n # ordering of entries does not mess with the `unique` database field constraint.\n class OrderedDictJSONDecoder(json.JSONDecoder):\n def __init__(self, *args, **kwargs):\n kwargs['object_pairs_hook']=collections.OrderedDict\n super().__init__(*args, **kwargs)\n property_values = models.JSONField(decoder=OrderedDictJSONDecoder, null=False, default=collections.OrderedDict, validators=[JSONSchemaValidator(schema=_properties_json_schema)])\n\n def save(self, *args, **kwargs):\n if not isinstance(self.property_values, collections.OrderedDict):\n self.property_values = collections.OrderedDict(sorted(self.property_values.items()))\n super().save(*args, **kwargs)\n\n class Meta:\n app_label = 'dtf'\n\n constraints = [\n models.UniqueConstraint(\n fields=['project', 'property_values'], \n name='unique_project_property_values'\n )\n ]\n\nclass TestReference(models.Model):\n \"\"\"\n Model to store references to every test\n\n The project is a foreign key\n The test_name is not, since the references can be from different test result \\\n objects. The test name will be the same though. The test_name must not be UNIQUE constraint though, in order to allow equally named tests from multiple projects to be saved\n \"\"\"\n _references_json_schema = {\n 'schema': 'http://json-schema.org/draft-07/schema#',\n 'definitions': {\n 'value': TestResult._value_json_schema\n },\n 'type': 'object',\n 'additionalProperties': {\n 'type': 'object',\n 'properties': {\n 'value': {\n 'oneOf': [\n {'$ref': '#/definitions/value'},\n {'type': 'null'}\n ]\n },\n 'source': {'type': 'integer'},\n },\n 'required': ['value'],\n 'additionalProperties': False\n }\n }\n\n reference_set = models.ForeignKey(ReferenceSet, on_delete=models.CASCADE, null=False, related_name=\"test_references\")\n test_name = models.CharField(max_length=100, blank=False)\n\n created = models.DateTimeField(default=timezone.now, editable=False, blank=True)\n last_updated = models.DateTimeField(auto_now=True)\n\n # maybe this should just have a testresult as a foreign key?\n references = models.JSONField(null=False, default=dict, validators=[JSONSchemaValidator(schema=_references_json_schema)])\n\n required_project_membership_role = {\n 'view' : 'guest',\n 'add' : 'developer',\n 'change' : 'developer',\n 'delete' : 'owner'\n }\n\n def update_references(self, new_references, default_source):\n for name, data in new_references.items():\n if data is not None:\n self.references[name] = {\n 'value': data['value'],\n 'source': default_source\n }\n elif name in self.references:\n del self.references[name]\n\n def get_reference_or_none(self, value_name):\n return self.references.get(value_name, None)\n\n def __str__(self):\n if self.reference_set:\n return f\"{self.test_name} [{self.reference_set.project.name}]\"\n return f\"{self.test_name} [None]\"\n\n class Meta:\n app_label = 'dtf'\n constraints = [\n models.UniqueConstraint(\n fields=['reference_set', 'test_name'], \n name='unique_test_reference_property'\n )\n ]\n\nclass Webhook(models.Model):\n project = models.ForeignKey(Project, on_delete=models.CASCADE, null=False, related_name=\"webhooks\")\n\n name = models.CharField(max_length=100, blank=False)\n url = models.URLField(null=False, blank=False)\n secret_token = models.CharField(max_length=200, null=False, blank=False)\n\n on_submission = models.BooleanField(default=True)\n on_test_result = models.BooleanField(default=True)\n on_reference_set = models.BooleanField(default=True)\n on_test_reference = models.BooleanField(default=True)\n\n required_project_membership_role = {\n 'view' : 'developer',\n 'add' : 'owner',\n 'change' : 'owner',\n 'delete' : 'owner'\n }\n\n def most_recent_status(self):\n recent_log = WebhookLogEntry.objects.filter(webhook=self).order_by('-created').first()\n if recent_log is None:\n return None\n return recent_log.response_status\n\n class Meta:\n app_label = 'dtf'\n\nclass WebhookLogEntry(models.Model):\n webhook = models.ForeignKey(Webhook, on_delete=models.CASCADE, null=False, related_name=\"logs\")\n\n created = models.DateTimeField(default=timezone.now, editable=False, blank=True)\n\n POSSIBLE_TRIGGERS = [\n (Submission.__name__, Submission.__name__),\n (TestResult.__name__, TestResult.__name__),\n (ReferenceSet.__name__, ReferenceSet.__name__),\n (TestReference.__name__, TestReference.__name__),\n ]\n\n trigger = models.CharField(choices=POSSIBLE_TRIGGERS, null=False, blank=False, max_length=20)\n\n request_url = models.URLField(null=False, blank=False)\n request_data = models.JSONField(null=False, blank=False)\n request_headers = models.JSONField(null=False, blank=False)\n\n response_status = models.IntegerField(null=False, blank=False)\n response_data = models.TextField(null=False, blank=False)\n response_headers = models.JSONField(null=False, blank=False)\n\n required_project_membership_role = {\n 'view' : 'owner',\n 'add' : 'owner',\n 'change' : 'owner',\n 'delete' : 'owner'\n }\n\n class Meta:\n app_label = 'dtf'\n","repo_name":"albertziegenhagel/django-testing-framework","sub_path":"dtf/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":18352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21139517852","text":"import os\nimport pymongo\nfrom datetime import datetime\n\n\nclient = pymongo.MongoClient(os.environ['mongo'])\ndb = client[os.environ['db']]\ncollection = db['news']\n\ncursor = collection.find({\"archived\": False})\n\nfor doc in cursor:\n diff = datetime.now() - doc['createdAt']\n if diff.total_seconds() >= 86400:\n collection.update_one(\n {\"_id\": doc[\"_id\"]}, \n {\"$set\": {\"archived\": True}}\n )\n print(doc['_id'], \" is archived\")\n","repo_name":"rishabhd1/news_crawler","sub_path":"scripts/archiveNews.py","file_name":"archiveNews.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"25752340707","text":"import turtle\n\nturt = turtle.Turtle()\nwin = turtle.Screen()\n\nwin.setup(800, 800)\nwin.bgcolor('ivory')\n\n\n# Create a turtle object\nturt = turtle.Turtle()\n\n# Set the turtle's speed\nturt.speed(1) # You can adjust the speed as needed\n\n\n# Draw the longer tower-like shape with a wider egg-like top\nturt.forward(150) # Base\nturt.left(90)\nturt.forward(80) # Vertical line\n\n# Draw the wider egg-like top\nturt.circle(100, 180) # 100 is the radius, and 180 is the extent (half circle)\n\n# Continue drawing the tower\nturt.forward(80) \nturt.left(90)\nturt.forward(150)\nturt.left(90)\nturt.forward(80) \n","repo_name":"yorkzap/ITAS2023Fall","sub_path":"ITAS-185/examples/more_classes/eg02_libraries.py","file_name":"eg02_libraries.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13298845734","text":"'''\n Contains some functions to preprocess the data used in the visualisation.\n'''\nimport pandas as pd\n\n\ndef convert_dates(dataframe):\n '''\n Converts the dates in the dataframe to datetime objects.\n\n Args:\n dataframe: The dataframe to process\n Returns:\n The processed dataframe with datetime-formatted dates.\n '''\n dataframe[\"Date_Plantation\"] = pd.to_datetime(dataframe[\"Date_Plantation\"])\n return dataframe\n\n\ndef filter_years(dataframe, start, end):\n '''\n Filters the elements of the dataframe by date, making sure\n they fall in the desired range.\n\n Args:\n dataframe: The dataframe to process\n start: The starting year (inclusive)\n end: The ending year (inclusive)\n Returns:\n The dataframe filtered by date.\n '''\n\n dataframe = dataframe[dataframe[\"Date_Plantation\"].dt.year >= start]\n dataframe = dataframe[dataframe[\"Date_Plantation\"].dt.year <= end]\n dataframe = dataframe.reset_index(drop=True)\n\n return dataframe\n\n\ndef summarize_yearly_counts(dataframe):\n '''\n Groups the data by neighborhood and year,\n summing the number of trees planted in each neighborhood\n each year.\n\n Args:\n dataframe: The dataframe to process\n Returns:\n The processed dataframe with column 'Counts'\n containing the counts of planted\n trees for each neighborhood each year.\n '''\n serie = dataframe.groupby([\"Arrond_Nom\", dataframe.Date_Plantation.dt.year]\n ).size()\n df = serie.rename(\"Counts\").to_frame()\n\n return df\n\n\ndef restructure_df(yearly_df):\n '''\n Restructures the dataframe into a format easier\n to be displayed as a heatmap.\n\n The resulting dataframe should have as index\n the names of the neighborhoods, while the columns\n should be each considered year. The values\n in each cell represent the number of trees\n planted by the given neighborhood the given year.\n\n Any empty cells are filled with zeros.\n\n Args:\n yearly_df: The dataframe to process\n Returns:\n The restructured dataframe\n '''\n\n # To pivot the dataframe we need to set index as Arrond_Nom\n yearly_df = yearly_df.reset_index().set_index(\"Arrond_Nom\")\n\n # Pivot to get the dataframe with the right format\n yearly_df = yearly_df.pivot_table(values=\"Counts\",\n index=yearly_df.index,\n columns=\"Date_Plantation\",\n aggfunc='first')\n # Fill NaN with 0:\n yearly_df = yearly_df.fillna(0)\n return yearly_df\n\n\ndef get_daily_info(dataframe, arrond, year):\n '''\n From the given dataframe, gets\n the daily amount of planted trees\n in the given neighborhood and year.\n\n Args:\n dataframe: The dataframe to process\n arrond: The desired neighborhood\n year: The desired year\n Returns:\n The daily tree count data for that\n neighborhood and year.\n '''\n\n # Filter dataframe by arond name\n dataframe = dataframe[dataframe[\"Arrond_Nom\"] == arrond]\n\n # Filter dataframe by year\n dataframe = dataframe[dataframe[\"Date_Plantation\"].dt.year == year]\n\n # Get daily values\n daily_values = dataframe.groupby([\"Date_Plantation\"]).size()\n\n # Fill all the inexistant dates with 0\n idx = pd.date_range(daily_values.index[0], daily_values.index[-1])\n daily_values.index = pd.DatetimeIndex(daily_values.index)\n daily_values = daily_values.reindex(idx, fill_value=0)\n\n return daily_values\n","repo_name":"RemiGonin/INF8880E_labs","sub_path":"tp3/src/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"71675508437","text":"# Check if the given elements are in the given range\nA=int(input(\"Enter the starting number of the range :\"))\nB=int(input(\"Enter the ending number of the range :\"))\narr=[]\n#populating the array\nn=int(input(\"How many elements will you enter :\"))\nfor i in range(n):\n e=eval(input(\"Enter the element %d :\"%(i+1)))\n arr.append(e)\nprint(\"The elements of the array :\")\n\nfor i in range(A,B+1):\n if i not in arr:\n print(\"No\")\n break\nelse:\n print(\"Yes\")","repo_name":"SRIVISHWA-P/Intern_training","sub_path":"week1/q15.py","file_name":"q15.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34991597459","text":"from romano_class import NumeroRomano\n\n\ncontinuar=True\ndeseo=True\nvalor=''\n\nwhile continuar:\n\n operacion = input(\"Convertir Entero a Romano:ingrese X\\nConvertir Romano a Entero:ingrese Y: \")\n\n\n if operacion == 'X':\n valor = int(input(\"por favor ingrese valor numerico: \"))\n \n obj = NumeroRomano(valor)\n print(f\"El valor de {obj.valor} es igual a {obj.representacion} \")\n \n elif operacion =='Y':\n valor = input(\"por favor ingrese valor romano: \")\n \n obj = NumeroRomano(valor)\n print(f\"El valor de {obj.valor} es igual a {obj.representacion} \")\n \n else:\n print(\"Ingrese X o Y por favor\")\n\n v = input(\"Deseas continuar s/n\")\n if v == \"n\" :\n continuar=False\n print(\"Fin del programa\")","repo_name":"ivanes79/romanos","sub_path":"prueba_romanos.py","file_name":"prueba_romanos.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4893284380","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nfrom gs_quant.session import GsSession\n# external users should substitute their client id and secret; please skip this step if using internal jupyterhub\nGsSession.use(client_id=None, client_secret=None, scopes=('run_analytics',)) \n\n# ### IR Implied Volatility Across Strikes\n# \n# We look at how the implied vol changes for swaptions with varying strikes but fixed expiries.\n\n# In[2]:\n\n\nfrom gs_quant.instrument import IRSwaption\nfrom gs_quant.common import PayReceive\nfrom gs_quant.markets.portfolio import Portfolio\nfrom gs_quant.risk import IRAnnualImpliedVol\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\npd.options.display.float_format = '{:,.0f}'.format\n\ndef moneyness_curve(expiration, termination, pay_rec, ccy, min_bps, max_bps, step_size):\n eval_range =np.arange(min_bps, max_bps + step_size, step_size).tolist()\n num_instr = len(termination)\n results = pd.DataFrame(index = eval_range)\n for i in range(num_instr):\n portfolios = Portfolio([IRSwaption(pay_or_receive=pay_rec, notional_currency=ccy, termination_date=termination[i], \n expiration_date=expiration[i], strike=f'ATMF+{eval_K}') for eval_K in eval_range])\n portfolios.resolve()\n name_i = expiration[i] + termination[i] +' '+ ccy +' '+ pay_rec\n results[name_i] = portfolios.calc(IRAnnualImpliedVol).to_frame().values * 10000 \n\n plt.figure(figsize=(8, 5))\n plt.plot(results)\n plt.xlabel('Moneyness (bps)')\n plt.ylabel('Implied Ann. Volatility (bps)')\n plt.legend(results.columns)\n\n# In[4]:\n\n\nexpiration = ['10y','15y']\ntermination = ['10y', '15y']\npay_rec = 'Pay'\nccy = 'USD'\nmin_bps = -300\nmax_bps = 300\nstep_size = 20\n\nmoneyness_curve(expiration, termination, pay_rec, ccy, min_bps, max_bps, step_size)\n","repo_name":"RIMEL-UCA/RIMEL-UCA.github.io","sub_path":"chapters/2023/Qualité logicielle dans les notebooks Jupyter/assets/python-scripts/0001_vol_moneyness_screen.py","file_name":"0001_vol_moneyness_screen.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"26805174430","text":"from math import *\r\nimport sys\r\ninput=sys.stdin.readline\r\nfrom random import*\r\np=[2,3,5,7,11,13,17,19,23,29,31,37,41]\r\n\r\ndef pow(x,y,p):\r\n if y<2:\r\n return (x**y)%p\r\n if y%2:\r\n return (pow(x,y//2,p)**2*x)%p\r\n else:\r\n return (pow(x,y//2,p)**2)%p\r\n\r\ndef mil(n,a):\r\n s,d=0,n-1\r\n while not d%2:\r\n s+=1\r\n d//=2\r\n x=pow(a,d,n)\r\n if x==1 or x+1==n:\r\n return True\r\n for i in range(s-1):\r\n x=pow(x,2,n)\r\n if x+1==n:\r\n return True\r\n return False\r\n\r\ndef pri(n):\r\n if n in p:\r\n return True\r\n if n==1 or not n%2:\r\n return False\r\n for k in p:\r\n if not mil(n,k):\r\n return False\r\n return True\r\n\r\ndef rh(n,c,d):\r\n return (n**2+c)%d\r\n\r\ndef rho(n):\r\n if pri(n):\r\n return n\r\n if n==1:\r\n return 1\r\n if not n%2:\r\n return 2\r\n x,c,d=randint(2,n-1),randint(1,n-1),1\r\n y=x\r\n while d==1:\r\n x=rh(x,c,n)\r\n y=rh(y,c,n)\r\n y=rh(y,c,n)\r\n d=gcd(n,abs(x-y))\r\n if d==n:\r\n return rho(n)\r\n if pri(d):\r\n return d\r\n return rho(d)\r\n\r\nfor i in range(int(input())):\r\n n=int(input())\r\n if n==4:\r\n print(1)\r\n continue\r\n a=[]\r\n while n!=1:\r\n x=rho(n)\r\n n//=x\r\n a.append(x)\r\n if len(a)!=len(list(set(a))):\r\n print(-1)\r\n else:\r\n print(factorial(len(a)))","repo_name":"chan120714/baekjoon","sub_path":"백준/Diamond/1770. 배수와 약수의 개수/배수와 약수의 개수.py","file_name":"배수와 약수의 개수.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5363991333","text":"import os\nfrom subprocess import DEVNULL, Popen\n\nfrom evdev import KeyEvent, UInput\nfrom evdev import ecodes as e\n\nfrom keyboard.constants import (code_char_map, shift_maps, control_maps,\n alt_maps, control_alt_maps)\n\n\ndef nothing(*_):\n pass\n\n\nclass Remaper():\n def __call__(\n self,\n character_maps,\n callback=nothing,\n actions=[KeyEvent.key_down, KeyEvent.key_up, KeyEvent.key_hold]):\n out = {}\n for f, t in character_maps.items():\n for v in actions:\n\n def write_key(t=t, v=v):\n self.remap_action(t, v)\n callback(v)\n\n out[(f, v)] = write_key\n return out\n\n def remap_action(self):\n raise NotImplementedError(\"remap_action must be implemented\")\n\n\nclass RemapPassThroughs(Remaper):\n def __init__(self, input_handler):\n self.input_handler = input_handler\n\n def remap_action(self, t, v):\n self.input_handler.send_event(t, v, True)\n\n\nclass RemapSystemCommand(Remaper):\n def remap_action(self, t, v):\n if v == KeyEvent.key_down:\n run_background(t)\n\n\nclass RemapModifierPress(Remaper):\n def __init__(self, input_handler, press_func):\n self.input_handler = input_handler\n self.press_func = press_func\n\n def remap_action(self, t, v):\n if v in (KeyEvent.key_down, KeyEvent.key_hold):\n self.press_func(t, flush=True)\n\n\nclass RemapString(Remaper):\n def __init__(self, input_handler):\n self.input_handler = input_handler\n\n def remap_action(self, t, v):\n if v == KeyEvent.key_down:\n #won't work for modifiers or other special characters\n for c in t:\n self.input_handler.press(c)\n self.input_handler.ui.syn()\n\n\nclass RemapCallable(Remaper):\n def remap_action(self, t, v):\n if v == KeyEvent.key_down:\n t()\n\n\nclass InputHandler():\n def __init__(self):\n self.ui = UInput()\n self.generate_remap_pass_throughs = RemapPassThroughs(self)\n self.generate_remap_system_command = RemapSystemCommand()\n self.generate_remap_string = RemapString(self)\n self.generate_remap_python_callable = RemapCallable()\n self.make_generate_remap_mod_press = \\\n lambda mod: RemapModifierPress(self, self.make_mod_press(mod))\n self.shift_press = self.make_mod_press('')\n self.control_press = self.make_mod_press('')\n self.alt_press = self.make_mod_press('')\n self.control_alt_press = self.make_mod_press(\n ['', ''])\n\n self.mod_combos = [(shift_maps, self.shift_press),\n (control_maps, self.control_press),\n (alt_maps, self.alt_press),\n (control_alt_maps, self.control_alt_press)]\n\n def send_event(self, values, press_type, flush=False):\n if isinstance(values, str):\n self.send_key(values, press_type)\n else:\n for key in values:\n self.send_key(key, press_type)\n if flush:\n self.ui.syn()\n\n def write(self, key, press_type, flush=False):\n self.write_raw(code_char_map.inverse[key], press_type, flush)\n\n def write_raw(self, code, press_type, flush=False):\n self.ui.write(e.EV_KEY, code, press_type)\n if flush:\n self.ui.syn()\n\n def send_key(self, key, press_type, flush=False):\n for mod_map, mod_press in self.mod_combos:\n if key in mod_map:\n if press_type != KeyEvent.key_up:\n mod_press(mod_map[key], flush)\n return\n self.write(key, press_type, flush)\n\n def press(self, key, flush=False):\n self.send_event(key, KeyEvent.key_down)\n self.send_event(key, KeyEvent.key_up, flush)\n\n def make_mod_press(self, mod):\n def mod_press(key, flush=False):\n self.send_event(mod, KeyEvent.key_down)\n self.press(key)\n self.send_event(mod, KeyEvent.key_up, flush)\n\n return mod_press\n\n\ndef alert(title, text=\"\", time=10):\n print(\"alert: {}\".format(title))\n os.system(\"notify-send -u critical -t {} '{}' '{}'\".format(\n time * 1000, title, text))\n\n\ndef run_background(command):\n try:\n Popen(command, stdout=DEVNULL).pid\n except Exception as e:\n print(\"Background command error:\", e)\n alert(\"BACKGROUND PROCESS ERROR\", str(e))\n\ndef debug_print(debug, *text):\n if debug:\n print(*text)\n\nif __name__ == '__main__':\n u_input = InputHandler()\n u_input.press('a')\n u_input.ui.syn()\n","repo_name":"rgreenblatt/keyboard","sub_path":"src/keyboard/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"72561654357","text":"def binSearch(arr, l, h, item):\r\n mid=(l+h)//2\r\n if arr[mid]==item:\r\n return mid\r\n if item < arr[mid]:\r\n binSearch(arr,l,mid-1,item)\r\n elif item > arr[mid]:\r\n binSearch(arr,mid+1,h,item)\r\n else:\r\n return -1\r\n#main function\r\n#if __name__==\"__main__\":\r\narr=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]\r\ndata=15 #int(input(\"Enter element to search: \"))\r\ni = binSearch(arr,0,20,data)\r\nif i==-1:\r\n print(\"Element not found!\")\r\nelse:\r\n print(\"Element found at index\",i,\"in the list\")\r\n\r\n","repo_name":"PrincSingh/common-programs","sub_path":"Python_progs/binsearch.py","file_name":"binsearch.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19905472210","text":"import socket\n\n'''\nThis example demonstrates a simple port scanner\nusing Python\n'''\n\n# create a socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver = 'tweakers.net' \n\ndef pscan(port): \n try:\n s.connect((server,port))\n return True\n except:\n return False \n\nports = [21,80,443]\n\n \nfor p in ports:\n if pscan(p):\n print('Port ',p,' is open!')\n else:\n print('Port ',p,' is closed!')\n","repo_name":"ro-per/Sockets-Python","sub_path":"simpleportscanner.py","file_name":"simpleportscanner.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"73432538196","text":"from typing import Any\n\n\nclass DefaultSentinel:\n pass\n\n\nclass Field:\n def __init__(self, name: str, type_: type, default: Any = DefaultSentinel()):\n self.name = name\n self.type_ = type_\n self.default = default\n\n\ndef parse_fields(cls: type) -> dict[str, Field]:\n annotations = cls.__annotations__\n class_dict = cls.__dict__\n fields = {}\n for name, value in annotations.items():\n if name in class_dict:\n fields[name] = Field(name, value, class_dict[name])\n else:\n fields[name] = Field(name, value)\n\n return fields\n\n\ndef create_parameters(fields: dict[str, Field], class_name: str) -> str:\n params = []\n defaults_started = False\n for field in fields.values():\n if isinstance(field.default, DefaultSentinel):\n default = \"\"\n if defaults_started:\n raise TypeError(\n \"Non-default argument follows default argument\"\n f\"for {class_name}.{field.name}\"\n )\n else:\n default = f\" = DefaultSentinel()\"\n defaults_started = True\n params.append(f\"{field.name}: {field.type_.__name__}{default}\")\n\n return \", \".join(params)\n\n\ndef create_assignments(cls: type) -> str:\n annotations = cls.__annotations__\n assignments = []\n for name in annotations:\n assignments.append(\n f\"\"\"\n if isinstance({name}, DefaultSentinel):\n self.{name} = copy.deepcopy(self._FIELDS[\"{name}\"].default)\n else:\n self.{name} = {name}\n \"\"\".strip(\n \"\\n\"\n )\n )\n\n return \"\\n\".join(assignments)\n\n\ndef my_dataclass(cls: type):\n fields = parse_fields(cls)\n setattr(cls, \"_FIELDS\", fields)\n parameters = create_parameters(fields, class_name=cls.__name__)\n\n new_init = f\"\"\"\ndef __init__(self{', ' if parameters else ''}{parameters}):\n import copy\n{create_assignments(cls)}\n if hasattr(self, '__post_init__'):\n self.__post_init__()\n\n\"\"\".strip()\n\n exec(new_init, globals(), locals())\n\n new_init_func = locals()[\"__init__\"]\n new_init_func.__name__ = \"__init__\"\n new_init_func.__qualname__ = f\"{cls.__name__}.__init__\"\n\n cls.__init__ = new_init_func\n\n return cls\n\n\n@my_dataclass\nclass Person:\n name: str\n age: int = 25\n friends: list[str] = [\"John\", \"Jane\"]\n\n def __post_init__(self):\n print(f\"Hello from {self.name}'s post init\")\n\n def greet(self):\n print(f\"Hello {self.name}\")\n\n\ndef main():\n john = Person(\"John\")\n john.greet()\n john.friends.append(\"Hugo\")\n print(john.friends)\n print()\n\n mary = Person(\"Mary\", 30)\n print(mary.friends)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"isaacharrisholt/youtube","sub_path":"022-recreating-dataclasses/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"5125148930","text":"from turtle import Turtle\nfrom random import choice, randrange\n\nCOLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\nSTARTING_MOVE_DISTANCE = 5\nMOVE_INCREMENT = 10\n\n\nclass CarManager(Turtle):\n def __init__(self,level_speed):\n super().__init__()\n self.shape(\"square\")\n self.penup()\n self.shapesize(stretch_wid=1, stretch_len=2)\n self.speed = STARTING_MOVE_DISTANCE\n self.car_list = []\n self.setheading(180)\n self.goto(310, randrange(-240, 265, 25))\n self.color(choice(COLORS))\n self.speed = level_speed\n\n def move(self):\n self.forward(self.speed)\n\n def speed_up(self):\n self.speed += MOVE_INCREMENT\n\n\n\n\n\n\n\n\n\n","repo_name":"Bajka3/Small-python-projects","sub_path":"crossing_street/car_manager.py","file_name":"car_manager.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7816327145","text":"#!/usr/bin/python3\n\n\n\n\n# -------- IMPORTATIONS --------\n\n#system\nimport sys, os, shutil\nSRC_DIR = os.path.dirname(os.getcwd())\nif SRC_DIR not in sys.path:\n\tsys.path.append(SRC_DIR)\n\n#tools\nfrom tools.general import *\n\n\n\n\n\n\n# -------- FUNCTIONS --------\n\n#create new project\ndef createNewProject(lab, project_path):\n\tif isPath(lab):\n\t\tproject_name = os.path.basename(project_path)\n\t\tfull_project_path = lab + '/' + project_path\n\n\t\t#check existence\n\t\tif os.path.exists(full_project_path):\n\t\t\tErr_fatal(\"Could not create project at location '\" + full_project_path + \"', element already exists.\")\n\n\t\t#check project name\n\t\tcheckIDName(project_name)\n\n\t\t#beginning message\n\t\tprint(\"Starting project creation at '\" + full_project_path + \"'...\")\n\n\t\t#copy project template\n\t\ttry:\n\t\t\tshutil.copytree(INSTALL_DIR + \"/templates/default/project\", full_project_path)\n\t\texcept (IOError, IsADirectoryError, FileNotFoundError):\n\t\t\tErr_fatal(\"Error creating new project (could not copy default template to destination).\")\n\n\t\t#replace action #PATH# in template\n\t\tf = open(full_project_path + \"/actions/settings.cfg\", \"r\")\n\t\tcontent = f.read()\n\t\tf.close()\n\t\tcontent = content.replace(\"#PATH#\", project_path + \"/actions\")\n\t\tf = open(full_project_path + \"/actions/settings.cfg\", \"w\")\n\t\tf.write(content)\n\t\tf.close()\n\n\t\t#find name for symlink to scheduler trigger (step 1: get the list of existing numbers)\n\t\tnew_number = 0\n\t\tnumbers_taken = []\n\t\tfor fse in os.path.listdir(lab + \"/scheduler/triggers\"):\n\t\t\tif os.path.isfile(fse) and Path_extension(fse) == \"cfg\" and isHexName(fse):\n\t\t\t\tnumbers_taken.append( int(Path_name(fse), 16) )\n\n\t\t#find name for symlink to scheduler trigger (step 2: count until the greatest one)\n\t\tif len(numbers_taken) != 0:\n\t\t\tnumbers_taken.sort()\n\t\t\tnew_number = -1\n\t\t\tfor n in range(numbers_taken[-1]+1):\n\t\t\t\tif n not in numbers_taken: #if one is missing : TAKING IT !\n\t\t\t\t\tnew_number = n\n\t\t\t\t\tbreak\n\n\t\t\t#find name for symlink to scheduler trigger (step 3: if no missing number found, take the next value)\n\t\t\tif new_number == -1:\n\t\t\t\tnew_number = numbers_taken[-1] + 1\n\n\t\t#create symlink for scheduler trigger\n\t\tif os.symlink(full_project_path + \"/actions/settings.cfg\", lab + \"/scheduler/triggers/\" + hex(new_number)[2:] + \".cfg\"):\n\t\t\tErr_fatal(\"Unable to create symbolic link for scheduler triggering.\")\n\n\t\t#end message\n\t\tprint(\"New project successfully created at '\" + full_project_path + \"'.\")\n\t\treturn\n\n\t#URL\n\tErr_fatal(\"URL request for project creation has not been implemented yet.\")\n","repo_name":"iasebsil83/TinyLabs","sub_path":"src/tools/create_new_project.py","file_name":"create_new_project.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13861652841","text":"import pygame\nfrom pygame.locals import *\nimport random\n\nwhite = (255, 255, 255)\nblack = (0, 0, 0)\nsalmon = (250, 128, 114)\nred = (255, 0, 0)\nblue = (0, 0, 255)\n\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\npygame.mixer.init()\n\npygame.font.init()\n\nclass Snake(pygame.sprite.Sprite):\n\n def __init__(self):\n super().__init__()\n self.body = []\n self.block_size = 20\n self.length = 4\n bs = self.block_size\n for i in range(self.length):\n self.body.append((SCREEN_WIDTH / 2 + i * bs, SCREEN_HEIGHT / 2))\n self.direction = (bs, 0)\n self.eat_food = False\n\n def die(self):\n n = len(self.body)\n loc = self.body[n - 1]\n bs = self.block_size\n if loc[0] < 0 or loc[0] > SCREEN_WIDTH - bs or loc[1] < 0 or loc[1] > SCREEN_HEIGHT - bs:\n return True\n elif loc in self.body[ : n - 1]:\n return True\n return False\n\n def turn(self, pressed_keys):\n bs = self.block_size\n if pressed_keys[K_UP] and self.direction != (0, bs):\n self.direction = (0, -bs)\n if pressed_keys[K_DOWN] and self.direction != (0, -bs):\n self.direction = (0, bs)\n if pressed_keys[K_LEFT] and self.direction != (bs, 0):\n self.direction = (-bs, 0)\n if pressed_keys[K_RIGHT] and self.direction != (-bs, 0):\n self.direction = (bs, 0)\n\n def update(self):\n if self.eat_food == False:\n self.body.pop(0)\n else:\n self.eat_food = False\n self.length += 1\n old_head = self.body[-1]\n dr = self.direction\n self.body.append((old_head[0] + dr[0], old_head[1] + dr[1]))\n\nclass Food(pygame.sprite.Sprite):\n \n def __init__(self, bs):\n super().__init__()\n self.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n self.range = (int(SCREEN_WIDTH / 2) // bs, int(SCREEN_HEIGHT / 2) // bs)\n self.block_size = bs\n c = self.center\n r = self.range\n self.loc = (c[0] + random.randint(-r[0]+ 1, r[0] - 2) * bs, c[1] + random.randint(-r[1] + 1, r[1] - 2) * bs)\n\n def update(self):\n c = self.center\n r = self.range\n bs = self.block_size\n self.loc = (c[0] + random.randint(-r[0]+ 1, r[0] - 2) * bs, c[1] + random.randint(-r[1] + 1, r[1] - 2) * bs)\n\ndef game_loop():\n\n clock = pygame.time.Clock()\n\n running = True\n\n playing = True\n\n while running:\n\n for event in pygame.event.get():\n if event.type == QUIT:\n running = False\n break\n elif event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n else:\n playing = True\n break\n \n snake = Snake()\n bs = snake.block_size\n food = Food(bs)\n surf = pygame.Surface((bs, bs))\n\n try:\n pygame.mixer.music.load(\"Play.mp3\")\n die_sound = pygame.mixer.Sound(\"Die.mp3\")\n except:\n try:\n pygame.mixer.music.load(\"Snake_demo/Play.mp3\")\n die_sound = pygame.mixer.Sound(\"Snake_demo/Die.mp3\")\n except:\n pygame.mixer.music.load(\"/Users/zephyr/Desktop/CS/SE/Snake_demo/Play.mp3\")\n die_sound = pygame.mixer.Sound(\"/Users/zephyr/Desktop/CS/SE/Snake_demo/Die.mp3\")\n\n die_sound.stop()\n pygame.mixer.music.play(loops = -1)\n \n\n while playing:\n \n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n playing = False\n running = False\n else:\n pressed_keys = pygame.key.get_pressed()\n snake.turn(pressed_keys)\n\n if food.loc in snake.body:\n snake.eat_food = True\n food.update()\n\n snake.update()\n\n if snake.die():\n playing = False\n pygame.mixer.music.pause()\n die_sound.play()\n\n clock.tick(1)\n screen.fill(black)\n font = pygame.font.Font(\"freesansbold.ttf\", 32)\n text = font.render(\"Game Over\", False, red)\n textRect = text.get_rect()\n textRect.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)\n screen.blit(text, textRect)\n pygame.display.update()\n\n clock.tick(0.5)\n screen.fill(black)\n text1 = font.render(\"Press Esc to exit\", False, red)\n text2 = font.render(\"Press any other key to continue\", False, red)\n textRect1 = text1.get_rect()\n textRect2 = text2.get_rect()\n d = 20\n textRect1.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - d)\n textRect2.center = (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + d)\n screen.blit(text1, textRect1)\n screen.blit(text2, textRect2)\n pygame.display.update()\n\n clock.tick(0.5)\n playing = False\n \n else:\n\n screen.fill(white)\n\n surf.fill(red)\n for loc in snake.body:\n screen.blit(surf, loc)\n\n surf.fill(black)\n screen.blit(surf, food.loc)\n\n caption = \"Score: \" + str(snake.length - 4)\n pygame.display.set_caption(caption)\n\n pygame.display.update()\n\n clock.tick(24 - 56 / snake.length) # number of frames\n\n pygame.quit()\n quit()\n\ngame_loop()","repo_name":"Zephyr271828/Snake-Game-demo","sub_path":"snake_demo.py","file_name":"snake_demo.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"14730606401","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nArduino HRV Capture Tool\n========================\n:File: arduino_hrv_capture_tool.py\n:Description: Captures Arduino HRV data from a USB serial port\n:Version: 0.0.1\n:Created: 2020-02-16\n:Authors: Jason Meno (jameno)\n:Dependencies: A .csv containing Tidepool CGM device data\n:License: BSD-2-Clause\n\"\"\"\nimport serial\nimport numpy as np\nimport time\nimport pandas as pd\nimport datetime\nimport sys\nfrom scipy.signal import find_peaks\nimport matplotlib.pyplot as plt\n\n# %% Record Data From Serial USB\nport_name = '/dev/cu.usbmodem14201'\nser = serial.Serial(port_name, 9600)\n\ntimestamp_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\nsignal_filename = 'heart_signal_' + timestamp_now + '.csv'\n#export_file = open(signal_filename, 'a')\n#export_file.write('timestamp,value\\n')\n\n# Sampling (100 samples/sec)\nrun_seconds = 180\nn_samples = 100 * run_seconds\n\nanimation_duration = run_seconds\ninhale_symbol = \"O\"\nexhale_symbol = \".\"\ninhale_seconds = 5\nexhale_seconds = 5\nfield_width = 70\n\ninhale_marker_times = np.linspace(0, inhale_seconds, field_width)\ninhale_symbol_num = np.ceil(\n (np.sin(np.linspace(-np.pi / 2, np.pi / 2, field_width)) + 1) * field_width / 2\n)\n\nexhale_marker_times = np.linspace(\n inhale_seconds, inhale_seconds + exhale_seconds, field_width\n)\nexhale_symbol_num = inhale_symbol_num * -1 + field_width # Inverse Signal\n\nstart_time = time.time()\ndiff_time = time.time() - start_time\nmod_time = diff_time % inhale_seconds\nprevious_marker_time = 0\n\nbreath_status = \"inhale\"\nprint_ready = False\n\nsignal_data = []\nbreath_data = []\n\nprint(\"Starting...\", end=\"\")\nfor x in range(n_samples):\n #output = str(time.time()) + \",\" + str(int(ser.readline())) + \"\\n\"\n signal = int(ser.readline())\n signal_data.append((time.time(), signal))\n\n # scaled_signal = int(signal/10)\n # output_string = \"Signal: [\" + 'O'*scaled_signal + '.'*(100-scaled_signal) + \"] \"\n # sys.stdout.write(\"\\r\" + output_string)\n # sys.stdout.flush()\n #export_file.write(output)\n\n if breath_status == \">>> INHALE >>>\":\n status = 1000\n marker_time = np.where(inhale_marker_times >= mod_time)[0][0]\n\n if marker_time > previous_marker_time:\n inhale_num = int(inhale_symbol_num[marker_time])\n exhale_num = field_width - inhale_num\n print_ready = True\n previous_marker_time = marker_time\n\n diff_time = time.time() - start_time\n mod_time = diff_time % (inhale_seconds + exhale_seconds)\n\n if mod_time > inhale_seconds:\n breath_status = \"<<< exhale <<<\"\n previous_marker_time = 0\n\n else:\n status = 0\n marker_time = np.where(exhale_marker_times >= mod_time)[0][0]\n\n if marker_time > previous_marker_time:\n inhale_num = int(exhale_symbol_num[marker_time])\n exhale_num = field_width - inhale_num\n print_ready = True\n previous_marker_time = marker_time\n\n diff_time = time.time() - start_time\n mod_time = diff_time % (inhale_seconds + exhale_seconds)\n\n if mod_time < inhale_seconds:\n breath_status = \">>> INHALE >>>\"\n previous_marker_time = 0\n\n if print_ready:\n breath_data.append((time.time(), inhale_num, status))\n state = inhale_symbol * inhale_num + exhale_symbol * exhale_num\n output_string = breath_status + \" [\" + state + \"] \" + breath_status\n sys.stdout.write(\"\\r\" + output_string)\n sys.stdout.flush()\n print_ready = False\n\nprint(\"Done!\")\n# export_file.close()\nser.close()\n# %% Load data and add local time information\n#data_df = pd.read_csv(signal_filename, low_memory=False)\n#data_df[\"local_time\"] = pd.to_datetime(data_df.timestamp,\n# unit='s',\n# utc=True).dt.tz_convert(time.tzname[0])\n#\n#data_df.to_csv(signal_filename, index=False)\n\n\n# %% Merge signals into one dataframe\nsignal_data = pd.DataFrame(signal_data, columns=['timestamp', 'value'])\nbreath_data = pd.DataFrame(breath_data, columns=['timestamp', 'stage', 'status'])\ndata = pd.concat([signal_data, breath_data], sort=False)\ndata[\"local_time\"] = pd.to_datetime(data['timestamp'],\n unit='s',\n utc=True).dt.tz_convert(time.tzname[0])\ndata.sort_values('local_time', ascending=True, inplace=True)\ndata[['stage','status']] = data[['stage','status']].fillna(method='ffill')\ndata = data[data['value'].notnull().values]\n\n# %% Viz peaks\n#signal_data = pd.DataFrame(signal_data)\n#signal_sample = signal_data[1]\n#peaks, thing = find_peaks(signal_sample, distance=50)\npeaks, thing = find_peaks(data['value'], distance=50)\nplt.plot(data['value'])\nplt.plot(peaks, data['value'][peaks], \"x\")\n\n# %% HRV\npd.Series(peaks).diff().rolling(3, center=True).mean().plot(figsize=(15,5))\npd.Series(data['stage'][peaks].values/2+60).plot(figsize=(15,5))\n\n# %% Viz peaks smoothed\ndata['smoothed_value'] = data['value'].rolling(1, center=True).mean()\npeaks, thing = find_peaks(data['smoothed_value'], distance=50)\n#plt.plot(signal_smoothed)\ndata['smoothed_value'].plot(figsize=(10,5))\n#plt.plot(peaks, pd.Series(signal_smoothed)[peaks], \"x\")\ndata['smoothed_value'][peaks].plot(figsize=(10,5),style=\"x\")\n# %% HRV\npd.Series(peaks).diff().plot(figsize=(10,5))\n\n# %% Ratio between inhale and exhale HRV\nhrv = pd.Series(peaks).diff()\ninhale_hrv = hrv[data['status'][peaks].values == 1000]\nexhale_hrv = hrv[data['status'][peaks].values == 0]\n\n# %%\ninhale_hrv.hist(bins=25, label='inhale')\nexhale_hrv.hist(bins=25, label='exhale')\nplt.legend()","repo_name":"jameno/T1D-HRV-Tools","sub_path":"src/arduino_hrv_capture_tool.py","file_name":"arduino_hrv_capture_tool.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"6111313686","text":"class Solution:\n def search(self, nums: List[int], target: int) -> int:\n init = 0\n end = len(nums)-1\n mid = 0\n while init <= end:\n mid = init + ((end - init) // 2)\n if nums[mid] > target:\n end = mid - 1\n elif nums[mid] < target:\n init = mid + 1\n else:\n return mid\n return -1\n","repo_name":"iamdiegosanches/codePrep","sub_path":"Python/Binary Search/binarySearch.py","file_name":"binarySearch.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32266331558","text":"import numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\n\nclass K_Means:\n def __init__(self, k, precision = 0.0001):\n self.k = k\n self.precision = precision\n self.dataNames = []\n self.boxes = {}\n \n def fitDefault(self,listComplexWave):\n self.boxes = self.fitDefaultProcess(listComplexWave)\n return self.boxes\n \n def fitDefaultProcess(self,listComplexWave):\n \n\t\t#initialize the centroids, the first distinct 'k' elements in the dataset will be our initial centroids \n centroids = self.initializeClustersFirstElements(listComplexWave,self.k)\n\n\t\t#begin iterations\n while True:\n boxes = {}\n for i in range(self.k):\n boxes[i] = []\n\n\t\t\t#find the distance between the point and cluster; choose the nearest centroid\n for wave in listComplexWave:\n \n distances = self.calculateDistancesDefault(wave,centroids)\n\n classification = distances.index(min(distances))\n boxes[classification].append(wave)\n previousCentroids = dict(centroids)\n\n\t\t\t#average the cluster datapoints to re-calculate the centroids\n isOptimal =self.averageCluster(previousCentroids,centroids,boxes)\n\t\t\t#break out of the main loop if the results are optimal, ie. the centroids don't change their positions much(more than our tolerance)\n if isOptimal:\n return boxes\n \n \n\t#initialize the centroids, the first distinct 'k' elements in the dataset will be our initial centroids \n def initializeClustersFirstElements(self, listComplexWave,k):\n output = {}\n i = 0\n j = 0\n while i < k :\n if j >= len(listComplexWave):\n #Case we run out of elements asignating centroids\n nextCentroid = max(output.values()) + 1\n else :\n nextCentroid = listComplexWave[j]\n \n j = j + 1\n if (not nextCentroid in output.values()):\n output[i] =nextCentroid\n i = i + 1\n for i in range(k):\n output[i] = listComplexWave[i].y\n return output\n \n #average the cluster datapoints to re-calculate the centroids and returs if we finish the proccess\n def averageCluster(self,previousCentroids,centroids,boxes):\n for classification in boxes:\n \n centroids[classification]=[] \n for i in range(len(boxes[classification])):\n centroids[classification].append(boxes[classification][i].y)\n \n if not centroids[classification]:\n #Error empty centroid\n centroids[classification] = [[0]*len(previousCentroids[0])]\n centroids[classification] = np.average(centroids[classification], axis = 0)\n\n\n for centroid in centroids:\n\n original_centroid = previousCentroids[centroid]\n curr = centroids[centroid]\n change = self.change(curr,original_centroid)\n \n if change > self.precision:\n return False\n return True\n \n #Catches to elements of the original_centoroid that are 0\n def change(self,curr,original_centroid):\n change = 0\n for i in range(len(original_centroid)):\n if original_centroid[i] != 0:\n change = change + (abs(((curr[i] - original_centroid[i])/original_centroid[i] )* 100.0))\n return change\n \n #Uses the norm of n dimensions to get distance\n def calculateDistancesDefault(self, wave, centroids):\n output = []\n for centroid in centroids:\n distance = []\n for i in range(len(wave.y)):\n distance.append(wave.y[i] - centroids[centroid][i])\n \n output.append(np.linalg.norm(distance))\n return output\n\n def paintAll(self,nrows,ncols):\n for i in self.boxes:\n print(\"---------- Box \"+str(i)+\" ----------\")\n self.paintBox(self.boxes[i],1,nrows,ncols,i)\n plt.show()\n \n def paintWave(self,y):\n sr = len(y)\n # sampling interval\n ts = 1.0/sr\n x = np.arange(0,1,ts)\n if len(x) != len(y):\n x = np.delete(x,0)\n \n \n plt.plot(x,y, 'k')\n \n \n \n \n def paintBox(self,box,ymax,nrows,ncols,pos):\n \n label=\"\"\n plt.subplot(nrows, ncols, pos+1)\n plt.title('Data of Box - '+ str(pos))\n plt.ylim(0,ymax)\n for i in range(len(box)):\n print(box[i].dataName)\n self.paintWave(box[i].y)\n label = label + \" \" + (box[i].dataName) + \" \"\n #ax[pos//nrows,pos%ncols].set_title('Data - '+label)\n #ax[pos//nrows,pos%ncols].set_title('Data of Box - '+str(pos))\n \n \n ","repo_name":"javiman555/TFG","sub_path":"src/model/objects/k_means/K_Means.py","file_name":"K_Means.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"72292673878","text":"import os\nimport subprocess as subp\nimport sys\n\nimport numpy as np\n\nfrom pyar.interface import SF, which\n\n\nclass OBabel(SF):\n def __init__(self, molecule, forcefield=None):\n\n if which('obabel') is None:\n print('setup OBabel path')\n sys.exit()\n\n super(OBabel, self).__init__(molecule)\n\n if not os.path.isfile(self.start_xyz_file):\n molecule.mol_to_xyz(self.start_xyz_file)\n self.optimized_coordinates = []\n self.energy = 0.0\n\n def optimize(self, max_cycles=350, gamma=0.0, restart=False, convergence='normal'):\n \"\"\"\n \"\"\"\n # TODO: Add a return 'CycleExceeded'\n\n with open('tmp.log', 'w') as logfile, open('tmp.xyz', 'w') as xyzfile:\n try:\n subp.check_call([\"obminimize\", \"-ff\", \"uff\", '-n',\n max_cycles, self.start_xyz_file],\n stdout=xyzfile, stderr=logfile)\n except subp.CalledProcessError as e:\n print('done')\n with open('tmp.xyz') as xyzfile, open(self.result_xyz_file, 'w') as result_xyz_file:\n for line in xyzfile:\n if 'WARNING' not in line:\n result_xyz_file.write(line)\n self.energy = self.get_energy()\n self.optimized_coordinates = self.get_coords()\n return True\n\n def get_coords(self):\n \"\"\"\n :return: It will return coordinates\n \"\"\"\n return np.loadtxt(self.result_xyz_file, dtype=float, skiprows=2, usecols=(1, 2, 3))\n\n def get_energy(self):\n \"\"\"\n \"\"\"\n with open(self.job_name + '.ene', 'w') as energy_file:\n out = subp.Popen([\"obenergy\", \"-ff\", \"uff\", self.result_xyz_file], stdout=energy_file, stderr=energy_file)\n output, error = out.communicate()\n poll = out.poll()\n exit_status = out.returncode\n if exit_status is None:\n with open(self.job_name + '.ene', 'r') as energy_file:\n return float(energy_file.readlines()[-1].split()[3])\n\n\ndef xyz_to_mopac_input(xyzfile, mopac_input_file, keyword=None):\n \"\"\"\n Convert xyz file to mopac input\n\n :param xyzfile: input xyz file\n :param mopac_input_file: Mopac input file to be written\n :param keyword: this is the keyword for optimizations. This parameter\n should be a strings of characters which are mopac keywords\n :return: It will not return anything. It will prepare the input file for\n the purpose given in the keyword. Note that babel will be used to prepare\n the input(.mop) file.\n \"\"\"\n keyword_line = '-xkPM7' if keyword is None else '-xk' + keyword\n with open('tmp.log', 'w') as fminp:\n subp.call([\"babel\", \"-ixyz\", xyzfile, \"-omop\", mopac_input_file, keyword_line], stderr=fminp, stdout=fminp)\n print(open('tmp.log').readlines()[0])\n os.remove('tmp.log')\n\n\ndef xyz_to_sdf_file(xyz_input_files, sdf_output_file):\n print(xyz_input_files)\n with open('tmp.log', 'w') as fminp:\n subp.call([\"babel\", \"-ixyz\"] + xyz_input_files + [\"-osdf\", sdf_output_file], stderr=fminp, stdout=fminp)\n os.remove('tmp.log')\n\n\ndef make_inchi_string_from_xyz(xyzfile):\n \"\"\"This function will make a inchi string from a xyz file with\n babel as the tools\n \"\"\"\n if os.path.isfile(xyzfile):\n with open('OBabel.log', 'w') as ferr:\n inchi = subp.check_output([\"babel\", \"-ixyz\", str(xyzfile), \"-oinchi\"], stderr=ferr)\n return inchi.decode(\"utf-8\").strip()\n else:\n raise IOError(\"file %s does not exists\" % xyzfile)\n\n\ndef make_smile_string_from_xyz(xyzfile):\n \"\"\"This function will make smile string from a xyz file.\n if more than one xyz file provide, it will return smiles\n in a list. if one xyz file supplied, it will return the\n string\n \"\"\"\n if os.path.isfile(xyzfile):\n with open('OBabel.log', 'w') as ferr:\n try:\n pre_smile = subp.check_output([\"babel\", \"-ixyz\", str(xyzfile), \"-osmi\", \"-xn\"], stderr=ferr)\n smile = pre_smile.decode(\"utf-8\").strip()\n except Exception as e:\n ferr.write(str(e))\n smile = ''\n return smile\n else:\n raise IOError(\"file %s does not exists\" % xyzfile)\n\n\ndef main(input_files):\n from pyar import Molecule\n for f in input_files:\n mol = Molecule.Molecule.from_xyz(f)\n g = OBabel(mol)\n g.optimize()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"anooplab/pyar","sub_path":"pyar/interface/babel.py","file_name":"babel.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"85"} +{"seq_id":"4272518549","text":"import numpy as np\nfrom scipy.ndimage import morphology\n\n\ndef to_numpy(x):\n if not (isinstance(x, np.ndarray) or x is None):\n if x.is_cuda:\n x = x.data.cpu()\n x = x.detach().numpy()\n return x\n\ndef surfd(input1, input2, sampling=1, connectivity=1):\n input_1 = np.atleast_1d(input1.astype(np.bool))\n input_2 = np.atleast_1d(input2.astype(np.bool))\n\n conn = morphology.generate_binary_structure(input_1.ndim, connectivity)\n\n S = input_1 ^ morphology.binary_erosion(input_1, conn)\n Sprime = input_2 ^ morphology.binary_erosion(input_2, conn)\n\n # ~s is the negative of s\n dta = morphology.distance_transform_edt(~S, sampling)\n dtb = morphology.distance_transform_edt(~Sprime, sampling)\n\n sds = np.concatenate([np.ravel(dta[Sprime != 0]), np.ravel(dtb[S != 0])])\n\n return sds\n\ndef metrics(mask_, gt_, sampling=1):\n lnot = np.logical_not\n land = np.logical_and\n\n true_positive = np.sum(land((mask_), (gt_)))\n false_positive = np.sum(land((mask_), lnot(gt_)))\n false_negative = np.sum(land(lnot(mask_), (gt_)))\n true_negative = np.sum(land(lnot(mask_), lnot(gt_)))\n\n M = np.array([[true_negative, false_negative],\n [false_positive, true_positive]]).astype(np.float64)\n metrics = {}\n metrics['Sensitivity'] = M[1, 1] / (M[0, 1] + M[1, 1] + 1e-5)\n metrics['Specificity'] = M[0, 0] / (M[0, 0] + M[1, 0] + 1e-5)\n metrics['Dice'] = 2 * M[1, 1] / (M[1, 1] * 2 + M[1, 0] + M[0, 1] + 1e-5)\n \n surf_dis = surfd(mask_, gt_, sampling)\n # add hausdorff distance metric\n if len(surf_dis)==0:\n metrics['Hausdorff'] = 0\n metrics['Mean Distance Error'] = 0\n else:\n metrics['Hausdorff'] = surf_dis.max()\n # add mean distance metric\n metrics['Mean Distance Error'] = surf_dis.mean()\n return np.array([metrics['Dice'], metrics['Hausdorff'], metrics['Mean Distance Error']])\n\n\ndef evalAllmetric(mask_, gt_, sampling=1):\n num_region = len(gt_)\n cur_metrics = []\n for num in range(0, int(num_region)):\n cur_metrics.append(metrics(mask_[num], gt_[num], sampling))\n cur_metrics = np.concatenate(cur_metrics)\n return cur_metrics\n\n\ndef det_jac(array):\n # (2,h,w)\n # (x,y)\n dx = np.roll(array, axis = -1, shift = -1) - array\n dy = np.roll(array, axis = -2, shift = -1) - array\n pos_jac = (1+dx[0]) * (1+dy[1]) - dx[1] * dy[0]\n return pos_jac\n\n\ndef gradient_det_jac(array):\n dx = np.roll(array, axis = -1, shift = -1) - array\n dy = np.roll(array, axis = -2, shift = -1) - array\n dis = np.sqrt(dx**2 + dy**2)\n return dis\n","repo_name":"MatheoWang/MLPTransformer","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33756161161","text":"from flask import request\nfrom flask_restx import Resource\nfrom app.main.service.cartitem_service import change_quantity,delete_cart_item\n\nfrom app.main.util.decorator import admin_token_required\nfrom ..util.dto import CartItemDto\nfrom typing import Dict\n\napi = CartItemDto.api\n_cartitem = CartItemDto.cartitem\n\n@api.route('//changeqty')\nclass CartItem(Resource):\n @admin_token_required\n @api.expect(_cartitem, validate=True)\n @api.doc(responses={\n 200: 'Success',\n 400: 'Bad Request',\n 403: 'Forbidden'\n })\n @api.doc('change quantity a cart item')\n @admin_token_required\n def put(self, cart_item_id):\n \"\"\"Change quantity a cart item\"\"\"\n data = request.json\n return change_quantity(data=data, cart_item_id=cart_item_id)\n\n@api.route('//')\nclass CartItem(Resource):\n @api.doc('delete_cart_item')\n @admin_token_required\n @api.doc(responses={\n 200: 'Success',\n 400: 'Bad Request',\n 403: 'Forbidden'\n })\n @admin_token_required\n def delete(self, cart_item_id):\n \"\"\"Delete a cart item\"\"\"\n data = request.json\n return delete_cart_item(cart_item_id=cart_item_id)","repo_name":"justinphan99/ecommerce","sub_path":"app/main/controller/cartitem_controller.py","file_name":"cartitem_controller.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"35830301972","text":"from typing import Union, Optional, Callable\nimport os\nfrom omegaconf import OmegaConf\nimport pandas as pd\nimport io\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, random_split\nfrom torchvision import transforms as T\nimport lightning as pl\nfrom PIL import Image\n\n#from deeplightning.utils.io_local import read_image\nfrom deeplightning.data.transforms.transforms import load_transforms\nfrom deeplightning.data.transforms._resize import Resize\nfrom deeplightning.utils.messages import info_message\n\n\ndef _extract_classes(metadata, class_labels_str, label2index):\n classes = metadata.loc[:, class_labels_str].apply(lambda x: x.idxmax(), axis=1)\n classes = [label2index[k] for k in classes]\n return classes\n\n\ndef _extract_masks(metadata, root):\n masks = [\"{}\".format(os.path.join(root, \"masks\", f\"{metadata.loc[i,'image']}_segmentation.png\")) for i in range(metadata.shape[0])]\n return masks\n\n\nclass HAM10000_dataset(Dataset):\n \"\"\"HAM10000 Dataset (\"Human Against Machine with 10000 training images\") \n for Image Classification and Semantic Segmentation.\n It contains dermatoscopic images from different populations, acquired and \n stored by different modalities. Cases include a representative collection \n of all important diagnostic categories in the realm of pigmented lesions.\n\n Statistics & Details\n --------------------\n - images and segmentation masks size: (width,height)=(600,450)\n - normalization constants for images: mean=(?,) and std=(?,)\n - number of samples: 10015\n - number of image classes: 7\n - number of segmentation classes: 7 ()\n |-------|-------------|------------------------------------------------------------------------------------------------------------|\n | label | no. samples | description |\n |-------|-------------|------------------------------------------------------------------------------------------------------------|\n | MEL | 1113 | melanoma |\n | NV | 6705 | melanocytic nevi |\n | BCC | 514 | basal cell carcinoma |\n | AKIEC | 327 | actinic keratoses and intraepithelial carcinoma / Bowen's disease |\n | BKL | 1099 | benign keratosis-like lesions (solar lentigines / seborrheic keratoses and lichen-planus like keratoses) |\n | DF | 115 | dermatofibroma |\n | VASC | 142 | vascular lesions (angiomas, angiokeratomas, pyogenic granulomas and hemorrhage) |\n |-------|-------------|------------------------------------------------------------------------------------------------------------|\n \n References\n ----------\n - Tschandl, P., Rosendahl, C., & Kittler, H. (2018). \"The HAM10000 \n dataset, a large collection of multi-source dermatoscopic images \n of common pigmented skin lesions\". Scientific data, 5(1), 1-9.\n - https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/DBW86T\n \n Arguments\n ---------\n cfg : configuration object\n transform : Transforms to be applied to images\n\n \"\"\"\n def __init__(self, \n task: str,\n root: str,\n transform: Union[Optional[Callable],None] = None,\n mask_transform: Union[Optional[Callable],None] = None,\n ):\n self.task = task\n self.root = root\n self.transform = transform\n self.mask_transform = mask_transform\n self.label2index = {\"MEL\":0, \"NV\":1, \"BCC\":2, \"AKIEC\":3, \"BKL\":4, \"DF\":5, \"VASC\":6}\n metadata = pd.read_csv(os.path.join(root, \"GroundTruth.csv\"))\n images = [\"{}\".format(os.path.join(root, \"images\", f\"{metadata.loc[i,'image']}.jpg\")) for i in range(metadata.shape[0])]\n \n class_labels_str = list(self.label2index.keys())\n self.data = pd.DataFrame()\n self.data[\"images\"] = images\n if task == \"ImageClassification\":\n self.data[\"labels\"] = _extract_classes(metadata, class_labels_str, self.label2index)\n elif task == \"SemanticSegmentation\":\n self.data[\"masks\"] = _extract_masks(metadata, root)\n\n def __len__(self):\n return self.data.shape[0]\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n sample = {}\n \n # Process inputs (images)\n sample[\"inputs_paths\"] = self.data.loc[idx, \"images\"]\n sample[\"inputs\"] = Image.open(sample[\"inputs_paths\"]).convert('RGB')\n\n if self.transform:\n sample[\"inputs\"] = self.transform(sample[\"inputs\"])\n \n # Process targets (labels or masks)\n if self.task == \"ImageClassification\":\n sample[\"labels\"] = self.data.loc[idx, \"labels\"]\n elif self.task == \"SemanticSegmentation\":\n sample[\"masks_paths\"] = self.data.loc[idx, \"masks\"]\n sample[\"masks\"] = Image.open(sample[\"masks_paths\"])#.convert('RGB')\n if self.mask_transform:\n # mask must be resized and converted to tensor \n # but no other transformations should be applied\n sample[\"masks\"] = self.mask_transform(sample[\"masks\"])\n # squeeze the channel dimension and convert to integer\n sample[\"masks\"] = sample[\"masks\"].squeeze(0).long()\n\n return sample\n \n\nclass HAM10000(pl.LightningDataModule):\n def __init__(self, cfg: OmegaConf):\n super().__init__()\n self.cfg = cfg\n\n # check that config params are set correctly\n assert cfg.data.num_channels == 3\n if cfg.task == \"ImageClassification\":\n assert cfg.data.num_classes == 7\n elif cfg.task == \"SemanticSegmentation\":\n assert cfg.data.num_classes == 2\n else:\n raise ValueError\n\n # define data transforms\n self.train_transforms = load_transforms(cfg=cfg, subset=\"train\")\n self.test_transforms = load_transforms(cfg=cfg, subset=\"test\")\n self.mask_transform = T.Compose(T.ToTensor())\n resize = self.cfg.data.train_transforms.resize\n if resize is not None:\n self.mask_transform = T.Compose([Resize(resize), T.ToTensor()])\n\n def prepare_data(self) -> None:\n pass\n\n def setup(self, stage) -> None:\n ds = HAM10000_dataset(\n task = self.cfg.task,\n root = self.cfg.data.root,\n transform = self.test_transforms,\n mask_transform = self.mask_transform,\n )\n self.train_ds, self.val_ds = random_split(ds, [0.8, 0.2])\n self.test_ds = self.val_ds\n self.train_ds.dataset.transform = self.train_transforms # overwrite\n\n info_message(\"Training set size: {:,d}\".format(len(self.train_ds)))\n info_message(\"Validation set size: {:,d}\".format(len(self.val_ds)))\n info_message(\"Testing set size: {:,d}\".format(len(self.test_ds)))\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(\n dataset = self.train_ds, \n batch_size = self.cfg.data.batch_size,\n shuffle = True,\n num_workers = self.cfg.data.num_workers,\n )\n\n def val_dataloader(self) -> DataLoader:\n return DataLoader(\n dataset = self.val_ds, \n batch_size = self.cfg.data.batch_size,\n shuffle = False,\n num_workers = self.cfg.data.num_workers,\n )\n\n def test_dataloader(self) -> DataLoader:\n return DataLoader(\n dataset = self.test_ds, \n batch_size = self.cfg.data.batch_size,\n shuffle = False,\n num_workers = self.cfg.data.num_workers,\n )","repo_name":"pme0/DeepLightning","sub_path":"deeplightning/data/dataloaders/vision/ham10000.py","file_name":"ham10000.py","file_ext":"py","file_size_in_byte":8099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"31232209557","text":"'''\nhttps://crocoder.dev/blog/map-filter-reduce-exercises/\n\nCount elements in an array of arrays\nCount the occurrences of distinct elements in the given 2D array.\nThe given input is an array, the elements of which are arrays of strings.\nThe result is a dictionary whose keys are the values from the arrays and \ntheir value is the number of their occurrences.\n\nExample\nInput: [\n ['a', 'b', 'c'],\n ['c', 'd', 'f'],\n ['d', 'f', 'g'],\n ]\nOutput: \n{\n a: 1,\n b: 1,\n c: 2,\n d: 2,\n f: 2,\n g: 1,\n }\n'''\n\nfrom functools import reduce\nfrom typing import Any\n\nfrom funcs import my_reduce\n\n\nflatten = lambda matrix: (i for array in matrix for i in array)\n\n\ndef count(frequencies: dict, element: Any) -> dict:\n if element in frequencies:\n return {\n **frequencies,\n element: frequencies[element] + 1\n }\n else:\n return {\n **frequencies,\n element: 1\n }\n\n\ninp = [\n ['a', 'b', 'c'],\n ['c', 'd', 'f'],\n ['d', 'f', 'g'],\n]\n\nprint(reduce(count, flatten(inp), {}))\nprint(my_reduce(flatten(inp), count, {}))\n","repo_name":"Davidi24/swe211-paradigms","sub_path":"2021-2022/Functional_Programming/high_order_functions/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"85"} +{"seq_id":"71600146199","text":"from .base import * # noqa\n\nDEBUG_APPS = [\"debug_toolbar\", \"django_extensions\"]\n\nINSTALLED_APPS = DEBUG_APPS + BASE_APPS # noqa\n\nMIDDLEWARE = [\n \"debug_toolbar.middleware.DebugToolbarMiddleware\",\n] + MIDDLEWARE # noqa\n\n\ndef show_toolbar(request):\n return True\n\n\nDEBUG_TOOLBAR_CONFIG = {\n \"SHOW_TOOLBAR_CALLBACK\": show_toolbar,\n}\n\n# for jupyter notebooks\nNOTEBOOK_ARGUMENTS = [\n \"--ip\",\n \"0.0.0.0\",\n \"--allow-root\",\n \"--no-browser\",\n]\n\nGRAPH_MODELS = {\n \"all_applications\": True,\n \"group_models\": True,\n}\n\n\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"handlers\": {\n \"console\": {\n \"level\": \"INFO\",\n \"class\": \"logging.StreamHandler\",\n \"stream\": \"ext://sys.stdout\",\n }\n },\n \"loggers\": {\n \"django\": {\n \"handlers\": [\"console\"],\n \"level\": os.getenv(\"DJANGO_LOG_LEVEL\", \"INFO\"), # noqa\n },\n },\n}\n","repo_name":"briancaffey/sec-filings-app","sub_path":"backend/backend/settings/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"85"} +{"seq_id":"2362268758","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 ('users', '0010_auto_20160207_1025'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tab',\n name='tab',\n field=models.CharField(choices=[('f', 'Friends'), ('fof', 'Friends of friends'), ('fmmf', 'Friends with most mutual friends'), ('fmml', 'Friends with most mutual likes')], max_length=4, unique=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"felix-d/social-commerce-project","sub_path":"users/migrations/0011_auto_20160207_1030.py","file_name":"0011_auto_20160207_1030.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"70895362839","text":"import sys\nsys.stdin = open('./그리디/강의/섹션 4/6. 씨름선수/씨름선수.txt','r')\n# sys.stdin = open('./그리디/강의/섹션 4/6. 씨름선수/in1.txt', 'r')\n\nspace = [] # 값들을 넣자.\nfor _ in range(int(input())):\n space.append(list(map( int, input().split() )))\n\nprint(space) # 처음 상태를 확인하자\nspace.sort(reverse = True) # 키 순서로 내림차순 정렬한다.\nprint(space) # 정렬 상태를 확인하자\n\ncnt = 0\nheavy = 0 # 현재 선택된 선수의 몸무게와 이전 선수들의 몸무게를 비교하여 가장 큰 값 저장\n\nfor height, weight in space:\n if weight > heavy: # 현재 선택된 선수의 몸무게와 이전 선수들의 몸무게를 비교\n heavy = weight # 현재 값으로 heavy 값을 업데이트 한다.\n cnt +=1\n\nprint(cnt)\n\n\n","repo_name":"meo4739/Coding_Test","sub_path":"그리디/강의/섹션 4/6. 씨름선수/AA.py","file_name":"AA.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20881727085","text":"print(\"Hello, this is a simple python program that stores your details\")\nanswer = input(\"Do you want to provide your details to me? /(yes or no/) \")\n\nif answer == \"no\" or answer == \"n\":\n print(\"Okay, so lets end this program\")\n exit()\nelif answer == \"yes\" or answer == \"y\":\n print(\"Okay, I am gonna ask you some questions\")\n user_name = input(\"Enter your name: \")\n user_age = input(\"Enter your age: \")\n gender_answer = input(\"Do you want me to ask you your gender? \")\n if gender_answer == \"yes\" or gender_answer == \"y\":\n user_gender = input(\"Enter your gender: \")\n elif gender_answer == \"no\" or gender_answer == \"n\":\n print(\"Okay, I am not gonna ask your gender\")\nprint(\"So I know a some details about you..\")\nprint(\"Your name is \" + user_name)\nprint(\"Your age is \" + user_age)\nif gender_answer == \"yes\" or gender_answer == \"y\":\n print(\"You are a \" + user_gender)\nelif gender_answer == \"no\" or gender_answer == \"n\":\n exit()\n","repo_name":"harinandan123/Python-stuff","sub_path":"Games/userdetailstorer.py","file_name":"userdetailstorer.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"22788861762","text":"import pygame\nfrom settings import *\n\nclass Item():\n ITEMS_MAP = [\n SPEED_ITEM,\n DAMAGE_ITEM\n ]\n\n def __init__(self, x, y, killed_bosses):\n self.x = x\n self.y = y\n self.width = 100\n self.height = 100\n self.killed_bosses = killed_bosses\n self.img = pygame.transform.scale(self.ITEMS_MAP[self.killed_bosses], (self.width, self.height))\n self.bonus = 'speed'\n\n if self.ITEMS_MAP[self.killed_bosses] == SPEED_ITEM:\n self.bonus = 'speed'\n elif self.ITEMS_MAP[self.killed_bosses] == DAMAGE_ITEM:\n self.bonus = 'damage'\n self.width = 160\n self.height = 160\n\n self.mask = pygame.mask.from_surface(self.img)\n\n def draw(self, window):\n self.img = pygame.transform.scale(self.ITEMS_MAP[self.killed_bosses], (self.width, self.height))\n window.blit(self.img, (self.x, self.y))\n","repo_name":"felixjoykind/Space-Invaders-Py","sub_path":"classes/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31851003626","text":"#二分法\ndef bin_search(li, val):\n low = 0\n high = len(li) - 1\n while low < +high: # 候选区还有值\n mid = (low + high) // 2\n if li[mid] == val:\n return mid # 返回下标\n elif li[mid] > val:\n high = mid - 1\n else: # li[mid] 0:\n file_path = \"data/misto/links/links_\" + d1 + \"_\" + d2 + \".txt\"\n with open(file_path, \"w+\") as f:\n for link in data:\n f.write(link + \"\\n\")\n\n\ndef get_data_from_page(driver, id, link):\n for i in range(5):\n try:\n driver.get(link)\n # time.sleep(1)\n a_links = driver.find_elements_by_tag_name(\"a\")\n\n for a in a_links:\n try:\n if a.text.lower().find(\"inteiro teor\") != -1:\n # print(a.get_attribute(\"href\"))\n\n a.click()\n time.sleep(1)\n break\n except Exception as e:\n print(e)\n\n # print(\"Getting Text\")\n tag_contents = driver.find_elements_by_class_name(\"unprintable\")\n\n for tag in tag_contents:\n return tag.text\n\n except Exception as e:\n print(\"Error L1\", e, link)\n\n time.sleep(60 * (1 + random.random()))\n\n\ndef thread_get_data(arg):\n driver = webdriver.Firefox()\n driver.minimize_window()\n\n time.sleep(10 * random.random())\n\n while True:\n th_id = random.randint(0, 100)\n base_path = \"data/misto/cases/split_\" + str(th_id)\n\n if not os.path.exists(base_path):\n os.mkdir(base_path)\n break\n\n try:\n count = 1\n total = len(arg)\n\n for link, id in arg:\n perc = round(100 * count / total, 2)\n now = datetime.datetime.now()\n print(now.strftime('%Y-%m-%d %H:%M:%S'), \"\\tThread\\t\", th_id, \":\\t\", perc, \"%\\t\", count, \"\\tof\\t\", total)\n text = get_data_from_page(driver, id, link)\n\n file_name = base_path + \"/\" + str(id) + \".txt\"\n\n with open(file_name, \"w+\") as f:\n f.write(text)\n\n count += 1\n\n except Exception as e:\n print(\"Error L2:\", e)\n\n driver.close()\n driver.quit()\n\n\ndef next_id(ids):\n id = random.randint(0, 100000)\n while id in ids:\n id = random.randint(0, 100000)\n\n return id\n\n\ndef download_documents():\n links = []\n ids = []\n with open(\"../data/misto/final_links.txt\", \"r\") as file_link:\n print(\"Getting links\")\n for line in tqdm.tqdm(file_link):\n link = line.replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n\n id = random.randint(0, 100000000)\n while id in ids:\n id = random.randint(0, 100000000)\n ids.append(id)\n\n links.append([link, id])\n\n splits = np.array_split(links, 15)\n\n pool = Pool(15)\n results = pool.map(thread_get_data, splits)\n pool.close()\n pool.join()\n\n\ndef merge_links2():\n list_files = glob.glob(\"data/misto/links/*.txt\")\n count = 0\n for file_path in tqdm.tqdm(list_files):\n with open(file_path) as f:\n for line in f:\n print(line.replace(\"\\n\", \"\"))\n count += 1\n\n print(count)\n\n\ndef thread_crawl(inters):\n driver = webdriver.Firefox()\n driver.minimize_window()\n\n for interval in inters:\n crawler(driver, interval)\n\n driver.close()\n driver.quit()\n\n x = 0\n while x == 0:\n time.sleep(60)\n\n\ndef merge_links():\n file_paths = []\n data_links = []\n\n for dirName, subdirList, fileList in os.walk(\"../data/misto/links\"):\n for fname in tqdm.tqdm(fileList):\n file_path = os.path.join(dirName, fname)\n if fname.find(\".txt\") != -1:\n file_paths.append(file_path)\n\n with open(file_path, \"r\") as link_file:\n for line in link_file:\n data_links.append(line)\n\n print(len(data_links))\n data_links = list(set(data_links))\n data_links = [link for link in data_links if link.find(\"https://www.jusbrasil.com.br/\") == -1]\n\n print(len(data_links))\n\n with open(\"../data/misto/final_links.txt\", \"w+\") as f:\n for link in data_links:\n f.write(link.replace(\"\\n\", \"\") + \"\\n\")\n\n\ndef jusbrasil_crawl():\n intervals = []\n t = datetime.date.today()\n date_finish = datetime.date(t.year, t.month, t.day)\n\n th_ids = []\n for i in range(2000):\n\n th_id = random.randint(0, 10000000000000000000)\n while th_id in th_ids:\n th_id = random.randint(0, 10000000000000000000)\n th_ids.append(th_id)\n\n date_in = date_finish + datetime.timedelta(days=-7)\n\n str_in = str(date_in.year) + \"-\" + str(date_in.month).zfill(2) + \"-\" + str(date_in.day).zfill(2)\n str_fin = str(date_finish.year) + \"-\" + str(date_finish.month).zfill(2) + \"-\" + str(date_finish.day).zfill(2)\n\n intervals.append([th_id, str_in, str_fin])\n date_finish = date_in + datetime.timedelta(days=-1)\n\n splits = np.array_split(intervals, 30)\n\n # for interval in intervals:\n # crawler(interval)\n\n pool = Pool(30)\n results = pool.map(thread_crawl, splits)\n pool.close()\n pool.join()\n\n","repo_name":"thiagordp/embeddings_in_law_paper","sub_path":"crawlers/crawler/webcrawler_jusbrasil_process.py","file_name":"webcrawler_jusbrasil_process.py","file_ext":"py","file_size_in_byte":7118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3557169443","text":"\"\"\"\nThis code is the implementation of training WGAN-GP.\n\nThis is implemeted with reference to following links.\n- https://github.com/znxlwm/pytorch-generative-model-collections\n- https://github.com/igul222/improved_wgan_training\n\"\"\"\n\nimport os\nimport sys\nimport math\n\nimport torch\nimport torchvision\nfrom torch import nn, optim\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import grad\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid, save_image\nfrom tensorboardX import SummaryWriter\n\nbase = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')\nsys.path.append(base)\nfrom misc import *\nfrom models import *\nfrom wgan_gp.options import TrainOptions\nfrom wgan_gp.utils import *\n\n\ndef main():\n\topt = TrainOptions().parse()\n\n\twriter = SummaryWriter(os.path.join(opt.log_dir, 'runs'))\n\n\t# dataset\n\tdataset = get_dataset(opt.dataset, train=True, input_size=opt.image_size, normalize=False, augment=False)\n\tlabels = get_labels(opt.dataset)\n\topt.num_classes = len(labels)\n\tloader = DataLoader(dataset, batch_size=opt.batch_size, shuffle=True, num_workers=opt.num_workers)\n\n\t# model\n\tG, C = get_wgan_gp(opt.nz, opt.nc, opt.nf, opt.image_size, opt.condition, opt.num_classes)\n\tG = G.to(opt.device)\n\tC = C.to(opt.device)\n\tif opt.cuda and torch.cuda.device_count() > 1:\n\t\tG = torch.nn.DataParallel(G)\n\t\tC = torch.nn.DataParallel(C)\n\n\t# optimizer\n\tG_optimizer = optim.Adam(G.parameters(), lr=opt.lr, betas=(opt.beta1, opt.beta2))\n\tC_optimizer = optim.Adam(C.parameters(), lr=opt.lr, betas=(opt.beta1, opt.beta2))\n\n\tif opt.resume:\n\t\topt.last_epoch = load_checkpoint(G, C, G_optimizer, C_optimizer, os.path.join(opt.log_dir, 'checkpoint.pth.tar'))\n\telse:\n\t\topt.last_epoch = 0\n\n\t# fixed z & t\n\tnum_classes_for_log = min(opt.num_classes, 10)\n\tnum_samples = num_classes_for_log * 10\n\tif opt.condition:\n\t\tfix_z = torch.zeros((num_samples, opt.nz)).to(opt.device)\n\t\tfor i in range(10):\n\t\t\tfix_z[i * num_classes_for_log] = torch.randn((1, opt.nz))\n\t\t\tfor j in range(1, num_classes_for_log):\n\t\t\t\tfix_z[i * num_classes_for_log + j] = fix_z[i * num_classes_for_log]\n\t\tfix_z = fix_z.to(opt.device)\n\n\t\ttemp_t = torch.tensor(range(num_classes_for_log))\n\t\tfix_t = temp_t.repeat(10)\n\t\tfix_t = fix_t.to(opt.device)\n\telse:\n\t\tfix_z = torch.randn((100, opt.nz)).to(opt.device)\n\t\tfix_t = None\n\n\t# train\n\titr = opt.last_epoch\n\trunning_EMD = 0.0\n\tif opt.condition:\n\t\trunning_AC_loss = 0.0\n\t\tac_loss = nn.CrossEntropyLoss()\n\ttimer = Timer(opt.num_itrs, opt.last_epoch)\n\n\twhile True:\n\t\tfor i, (x_real, t) in enumerate(loader):\n\t\t\tif x_real.size(0) != opt.batch_size:\n\t\t\t\tbreak\n\n\t\t\tx_real = normalize(x_real.to(opt.device), None, opt.device)\n\t\t\tz = torch.randn((opt.batch_size, opt.nz)).to(opt.device)\n\t\t\tif opt.condition:\n\t\t\t\tt = t.to(opt.device)\n\n\t\t\t# === update C network === #\n\t\t\tG.eval()\n\t\t\tC.train()\n\n\t\t\tif opt.condition:\n\t\t\t\tC_real, y_real = C(x_real)\n\t\t\t\tC_real = torch.mean(C_real)\n\t\t\t\tAC_real_loss = ac_loss(y_real, t)\n\n\t\t\t\tx_fake = G(z, t).detach()\n\t\t\t\tC_fake, y_fake = C(x_fake)\n\t\t\t\tC_fake = torch.mean(C_fake)\n\t\t\t\tAC_fake_loss = ac_loss(y_fake, t)\n\n\t\t\t\tAC_loss = AC_real_loss + AC_fake_loss\n\t\t\telse:\n\t\t\t\tC_real = C(x_real)\n\t\t\t\tC_real = torch.mean(C_real)\n\n\t\t\t\tx_fake = G(z).detach()\n\t\t\t\tC_fake = C(x_fake)\n\t\t\t\tC_fake = torch.mean(C_fake)\n\n\t\t\t# EMD\n\t\t\tEMD = C_real - C_fake\n\n\t\t\t# gradient penalty\n\t\t\talpha = torch.rand((opt.batch_size, 1, 1, 1)).to(opt.device)\n\t\t\tx_hat = alpha * x_real.data + (1 - alpha) * x_fake.data\n\t\t\tx_hat.requires_grad = True\n\n\t\t\tif opt.condition:\n\t\t\t\tC_hat, _ = C(x_hat)\n\t\t\telse:\n\t\t\t\tC_hat = C(x_hat)\n\n\t\t\tgradients = grad(outputs=C_hat, inputs=x_hat, grad_outputs=torch.ones(C_hat.size()).to(opt.device), create_graph=True, retain_graph=True, only_inputs=True)[0]\n\t\t\tGP = opt.lambda_gp * ((gradients.view(gradients.size(0), -1).norm(2, dim=1) - 1) ** 2).mean()\n\n\t\t\tif opt.condition:\n\t\t\t\tC_loss = -EMD + GP + AC_loss\n\t\t\telse:\n\t\t\t\tC_loss = -EMD + GP\n\t\t\t\n\t\t\tC_optimizer.zero_grad()\n\t\t\tC_loss.backward()\n\t\t\tC_optimizer.step()\n\n\n\t\t\tif ((i + 1) % opt.num_critic) == 0:\n\t\t\t\titr += 1\n\n\t\t\t\t# === update G === #\n\t\t\t\tG.train()\n\t\t\t\tC.eval()\n\n\t\t\t\tif opt.condition:\n\t\t\t\t\tx_fake = G(z, t)\n\t\t\t\t\tC_fake, y_fake = C(x_fake)\n\t\t\t\t\tC_fake = torch.mean(C_fake)\n\t\t\t\t\tAC_fake_loss = ac_loss(y_fake, t)\n\t\t\t\t\tG_loss = -C_fake + AC_fake_loss\n\t\t\t\telse:\n\t\t\t\t\tx_fake = G(z)\n\t\t\t\t\tC_fake = C(x_fake)\n\t\t\t\t\tC_fake = torch.mean(C_fake)\n\t\t\t\t\tG_loss = -C_fake\n\n\t\t\t\tG_optimizer.zero_grad()\n\t\t\t\tG_loss.backward()\n\t\t\t\tG_optimizer.step()\n\n\t\t\t\t# log\n\t\t\t\tG.eval()\n\t\t\t\trunning_EMD += EMD.item()\n\t\t\t\tif opt.condition:\n\t\t\t\t\trunning_AC_loss += AC_loss.item()\n\t\t\t\tcommandline_output = ''\n\n\t\t\t\ttimer.step()\n\t\t\t\telapsed_time = timer.get_elapsed_time()\n\t\t\t\testimated_time = timer.get_estimated_time()\n\n\t\t\t\tif itr % 10 == 0:\n\t\t\t\t\tsamples = G(fix_z, fix_t).detach()\n\t\t\t\t\tsave_image(unnormalize(samples, None, opt.device), os.path.join(opt.log_dir, 'latest.png'), nrow=num_classes_for_log)\n\t\t\t\t\tcommandline_output = '\\r\\033[K[itr {:d}] EMD: {:.4f}'.format(int(itr), EMD.item())\n\t\t\t\t\tif opt.condition:\n\t\t\t\t\t\tcommandline_output += ', AC_loss: {:.4f}'.format(AC_loss.item())\n\t\t\t\t\tcommandline_output += ', elapsed time: {}, estimated time: {}'.format(elapsed_time, estimated_time)\n\n\t\t\t\t\tif itr % 1000 == 0:\n\t\t\t\t\t\tsave_image(unnormalize(samples, None, opt.device), os.path.join(opt.log_dir, '{:06d}itr.png'.format(int(itr))), nrow=num_classes_for_log)\n\t\t\t\t\t\tcommandline_output = '\\r\\033[K[itr {:d}] EMD: {:.4f}'.format(int(itr), running_EMD / 1000)\n\t\t\t\t\t\tif writer is not None:\n\t\t\t\t\t\t\twriter.add_scalars('Loss', {'EMD': running_EMD / 1000}, global_step=itr)\n\t\t\t\t\t\t\twriter.add_image('generated samples', make_grid(unnormalize(samples, None, opt.device), nrow=num_classes_for_log), global_step=itr)\n\t\t\t\t\t\trunning_EMD = 0.0\n\t\t\t\t\t\tif opt.condition:\n\t\t\t\t\t\t\tcommandline_output += ', AC_loss: {:.4f}'.format(running_AC_loss / 1000)\n\t\t\t\t\t\t\tif writer is not None:\n\t\t\t\t\t\t\t\twriter.add_scalars('Loss', {'AC_loss': running_AC_loss / 1000}, global_step=itr)\n\t\t\t\t\t\t\trunning_AC_loss = 0.0\n\t\t\t\t\t\tcommandline_output += ', elapsed time: {}, estimated time: {}\\n'.format(elapsed_time, estimated_time)\n\n\t\t\t\t\tdel samples\n\n\t\t\t\tsys.stdout.write(commandline_output)\n\t\t\t\tsys.stdout.flush()\n\n\t\t\t\t# save model\n\t\t\t\tsave_checkpoint(G, C, G_optimizer, C_optimizer, itr, os.path.join(opt.log_dir, 'checkpoint.pth.tar'))\n\n\t\t\tif itr == opt.num_itrs:\n\t\t\t\tbreak\n\n\t\tif itr == opt.num_itrs:\n\t\t\tbreak\n\n\tsave_model(G, os.path.join(opt.log_dir, 'G_weight_final.pth'))\n\tsave_model(C, os.path.join(opt.log_dir, 'C_weight_final.pth'))\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"takahiro-itazuri/Empirical_Study_of_Latent_Space_Adversary","sub_path":"wgan_gp/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6520,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"73173546519","text":"from typing import List\n\nfrom backend.model.Record import Record\nfrom backend.model.Event import Event\nfrom backend.utils.JsonHelper import JsonHelper\nfrom config import PAST_PATH\n\n\nclass PastDao:\n\n def __init__(self):\n self.cache = JsonHelper.loadJson(PAST_PATH)\n\n def getRecords(self) -> List[Record]:\n l = []\n for d in self.cache[\"records\"]:\n l.append(Record.deSerialize(d))\n\n return l\n\n def getRecordByIndex(self, index: int) -> Record:\n l = self.cache[\"records\"]\n\n if index < 0 or index >= len(l):\n return\n\n return Record.deSerialize(l[index])\n\n def getLastRecord(self) -> Record:\n l = self.cache[\"records\"]\n\n if len(l) == 0:\n return\n\n return Record.deSerialize(l[len(l) - 1])\n\n def insertRecordIntoCache(self, record: Record):\n self.cache[\"records\"].append(record.serialize())\n\n def deleteRecordByIndexFromCache(self, index: int):\n l = self.cache[\"records\"]\n\n if index < 0 or index >= len(l):\n return\n\n del l[index]\n\n def deleteAll(self):\n self.cache = {\"records\": []}\n\n def persist(self):\n JsonHelper.dumpToJson(self.cache, PAST_PATH)\n\n\npastDao = PastDao()\n\nif __name__ == \"__main__\":\n e = Event(\"\", \"\", True)\n l = [e, e]\n pastDao.insertRecordIntoCache(Record(l, \"2020\"))\n pastDao.deleteRecordByIndexFromCache(0)\n pastDao.persist()\n pass","repo_name":"Charipoter/PyQtToDoList","sub_path":"backend/dao/PastDao.py","file_name":"PastDao.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15765922673","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\n\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'myhouserent.views.mainindex', name='mainindex'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^user/', include('loginapp.urls', namespace=\"loginapp\")),\n url(r'^houseowner/', include('houseowner.urls', namespace=\"houseowner\")),\n url(r'^renterinfo/', include('Renter.urls', namespace=\"Renter\")), \n url(r'^rentdetails/', include('Rentdetails.urls', namespace=\"Rentdetails\")), \n url(r'^admin/', include(admin.site.urls)),\n)\n\nurlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n \n)","repo_name":"gtrdotmcs/myhouserent","sub_path":"myhouserent/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"31557486966","text":"# [0. 날짜]\n# 2021.08.06(금요일)\n# 문제 유형: DP\n# 걸린 시간: 1시간\n# [1. 문제의 간단한 해법과 함께 어떤 방식으로 접근했는지]\n# Scv의 체력이 60이므로\n# Scv의 개수만큼의 차원 배열을 만듭니다 개수가 2개면 2차원 3개면 3차원으로\n# 그리고 bfs로 완전탐색에 메모이제이션을 적용해서 풉니다\n# bfs 돌때 첫번째 scv, 두번째 scv, 세번쨰 scv로 공격하는 경우의 수를 탐색합니다.\n#\n# [2. 문제의 해법을 찾는데 결정적이었던 깨달음은 무엇이었는지]\n# 메모이제이션을 일관되게 조회하기 위해서 scvs_health 리스트의 길이를 3개로 맞춰주었다.\n# [3. +개선 사항]\n#\n# [4. +한번에 맞추지 못한 경우 오답 원인 적기]\n\nfrom collections import deque\n\n\ndef sol():\n damage_cases = []\n\n def dfs(visited):\n if len(visited) == N:\n damage_cases.append(visited[:])\n for i in range(N):\n damage = [9, 3, 1][i]\n if damage not in visited:\n visited.append(damage)\n dfs(visited)\n visited.pop()\n\n dfs([])\n damage_memo = [[[0 for _ in range(61)] for _ in range(61)] for _ in range(61)]\n q = deque([(scvs_health, 0)])\n while q:\n cur_scvs_health, attack_cnt = q.popleft()\n a, b, c = cur_scvs_health\n if not any(cur_scvs_health):\n return attack_cnt\n for damage_case in damage_cases:\n next_scvs_health = []\n for i in range(N):\n health = cur_scvs_health[i] - damage_case[i]\n next_scvs_health.append(health if health > 0 else 0)\n for _ in range(3 - N):\n next_scvs_health.append(0)\n na, nb, nc = next_scvs_health\n if damage_memo[na][nb][nc]:\n continue\n damage_memo[na][nb][nc] = 1\n q.append((next_scvs_health, attack_cnt + 1))\n\n\nN = int(input()) # SCV의 수\nscvs_health = list(map(int, input().split()))\nfor _ in range(3 - N):\n scvs_health.append(0)\nprint(sol())\n","repo_name":"hyunjune-lee/python_algorithm_interview","sub_path":"코딩테스트 대비를 위한 백준 문제 추천/BOJ_12869 - 뮤탈리스크.py","file_name":"BOJ_12869 - 뮤탈리스크.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"18560776176","text":"from pathlib import Path\nimport pickle\n\nimport tqdm\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom jax import random\n\nfrom research.estop.gym.ddpg_training import (deterministic_policy,\n make_default_ddpg_train_config,\n build_env_spec, rollout,\n debug_run)\nfrom research.estop.gym.half_cheetah import env_name, reward_adjustment\n\ninput_results_dir = Path(\"results/13_ed7ee131_ddpg_half_cheetah\")\n\nnum_support_set_rollouts = 128\n\nnum_episodes = 10000\npolicy_evaluation_frequency = 100\npolicy_video_frequency = 1000\n\n# This is assuming that we used the default train config. If not, well... don't\n# do that.\nenv_spec = build_env_spec(env_name, reward_adjustment)\ntrain_config = make_default_ddpg_train_config(env_spec)\n\ndef run_expert_rollouts(rng) -> np.ndarray:\n print(\"Loading vanilla DDPG results...\")\n experiment_metadata = pickle.load(\n (input_results_dir / \"metadata.pkl\").open(\"rb\"))\n\n data = [\n pickle.load((input_results_dir / f\"seed={seed}\" / \"data.pkl\").open(\"rb\"))\n for seed in tqdm.trange(experiment_metadata[\"num_random_seeds\"])\n ]\n final_policy_values = np.array([x[\"policy_evaluations\"][-1] for x in data])\n best_seed = int(np.argmax(final_policy_values))\n print(f\"... best seed is {best_seed}\"\n f\"with cumulative reward: {data[best_seed]['policy_evaluations'][-1]}\")\n\n print(\"Rolling out trajectories from best policy...\")\n actor_params, _ = data[best_seed][\"final_params\"]\n expert_policy = deterministic_policy(train_config, actor_params)\n return np.array([\n rollout(env_spec, r, expert_policy)[0]\n for r in tqdm.tqdm(random.split(rng, num_support_set_rollouts))\n ])\n\ndef get_estop_bounds(expert_rollouts):\n # Unfortunately there are a few special cases that need to be taken into\n # account here:\n # * Index 1 corresponds to an angle and so any multiple of 2 pi is actually\n # equivalent. Instead of mod'ing out this effect we just prune a bit more.\n # * Index 8 corresponds to the velocity, which we shouldn't really bound on\n # the max end. And on the min end we cannot trim anything off since we get\n # initialized at zero.\n percentiles = [1, 5, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1]\n state_min = np.array([\n np.percentile(expert_rollouts[:, :, i], p)\n for i, p in enumerate(percentiles)\n ])\n state_max = np.array([\n np.percentile(expert_rollouts[:, :, i], 100 - p)\n for i, p in enumerate(percentiles)\n ])\n std = np.std(expert_rollouts, axis=(0, 1))\n return state_min - std, state_max + std\n\ndef main():\n rng = random.PRNGKey(0)\n\n expert_rollouts = run_expert_rollouts(rng)\n expert_rollouts_flat = np.reshape(expert_rollouts,\n (-1, expert_rollouts.shape[-1]))\n state_min, state_max = get_estop_bounds(expert_rollouts)\n\n # Debug plot!\n plt.figure()\n for i in range(17):\n ax = plt.subplot(2, 9, i + 2)\n plt.hist(expert_rollouts_flat[:, i], bins=256)\n ax.yaxis.set_ticklabels([])\n plt.title(i)\n plt.axvline(state_min[i], c=\"r\")\n plt.axvline(state_max[i], c=\"r\")\n\n plt.show()\n\n debug_run(env_spec,\n train_config,\n seed=0,\n state_min=state_min,\n state_max=state_max)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"samuela/e-stops","sub_path":"research/estop/gym/half_cheetah/ddpg/debug_run_estop.py","file_name":"debug_run_estop.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"71867656598","text":"import pandas as pd\nfrom chemical.FingerPrint import Smiles2Hash\nfrom sampling.sampling import sampleMaxmin\nfrom chemical.FingerPrint import Hash2FingerPrint\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 17 12:00:07 2019\n\n@author: matsumoto\n\"\"\"\n\ndef MakeTrain(dict_data, testid, exid=None):\n \"\"\"\n devide from dictionary into training and test\n testid : select test data key\n \"\"\"\n #n_data = max(dict_data.keys())\n dict_key = list(dict_data.keys())\n if exid is not None:\n valid_keys = [key for key in dict_key if not key in exid]\n else:\n valid_keys = dict_key\n concat_list = [i for i in valid_keys if i != testid]\n \n df_tr = pd.DataFrame()\n df_ts = pd.DataFrame()\n \n for i in concat_list:\n df_tr = df_tr.append(dict_data[i])\n df_ts = dict_data[testid]\n \n return df_tr, df_ts\n\n\ndef AllDataDict(path, n_data, index=None, sep=','):\n \n \"\"\"\n read the all file in a folder and concatenate them as dictionary\n path : must be including number(i) because {}.format(i) is used in fanction\n \"\"\"\n DF = dict()\n \n for i in range(1, n_data+1):\n df = pd.read_csv(path.format(i), index_col=index, sep=sep)\n DF[i] = df\n \n return DF\n\n\ndef HashAllDataDict(path, n_data, ic50col, smilecol, index=None, sep=','):\n \"\"\"\n funtion is almost the same as ALLDataDict\n Furthermore, convert Smiles to Hash and concatenate with IC50 values\n \"\"\"\n n_DF = dict()\n for i in range(1, n_data+1):\n df = pd.read_csv(path.format(i), index_col=index, sep=sep)\n ic50 = df[ic50col]\n smiles = df[smilecol]\n \n hsh = Smiles2Hash(smiles)\n n_df = pd.concat([ic50, hsh], axis=1)\n \n n_df.rename(columns={smilecol:\"hash\"}, inplace=True)\n n_DF[i] = n_df\n \n return n_DF\n\n\ndef tr_ts_split(data, idx_tr=None, train_size=None, train_num=None, random_state=None):\n \"\"\"\n split into train and test including specified data in train\n if you include specified data in train, you specify its index using parameter idx_tr\n \"\"\"\n if train_size is not None:\n sample = round(len(data) * train_size) - len([idx_tr])\n temp = data.drop(index = idx_tr)\n tr_temp = temp.sample(n = sample, random_state = random_state)\n \n tr = tr_temp.append(data.loc[idx_tr])\n ts = data.drop(index = tr.index)\n \n elif train_num is not None:\n temp = data.drop(index = idx_tr)\n tr_temp = temp.sample(n = train_num-len([idx_tr]), random_state = random_state)\n \n tr = tr_temp.append(data.loc[idx_tr])\n ts = data.drop(index = tr.index)\n \n return tr, ts\n\n\ndef tr_ts_split_ks(data, idx_tr=None, train_num=None, random_state=0, fpcol='hash'):\n \"\"\"\n split into train and test including specified data in train based on kennerdstones\n if you include specified data in train, you specify its index using parameter idx_tr\n \"\"\"\n datafp = Hash2FingerPrint(data[fpcol])\n temp = datafp.drop(index = idx_tr)\n n = train_num - len([idx_tr])\n \n idx = sampleMaxmin(x_org=temp, n_sample=n, seed=random_state)\n idx = list(idx)\n idx.append(idx_tr)\n \n tr = data.loc[idx]\n ts = data.drop(index = idx)\n \n return tr, ts\n\n\ndef idx_check(data):\n new_data = pd.DataFrame()\n \n for asy_idx, assay in enumerate(data.Assay.unique()):\n data_2 = data.query(\"Assay == @assay\")\n data_2[\"Assay_idx\"] = asy_idx\n new_data = pd.concat([new_data, data_2], axis=0)\n \n return new_data\n","repo_name":"katsuhisam/my_function","sub_path":"Dataset/DataPreparation.py","file_name":"DataPreparation.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3181096780","text":"from global_ import *\nfrom global_var_ import MINIMUM_SEEN_MOVIES, MINIMUM_SEEN_USERS\n\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nfrom sklearn.preprocessing import MultiLabelBinarizer\nimport scipy\nfrom tqdm import tqdm\nimport itertools as it\n\n\n# Loading data\ndef load_data(path, dataset_type=\"small\"):\n\tif dataset_type == \"small\":\n\t\tmovies = pd.read_csv(path + \"ml-latest-small/movies.csv\")\n\t\tratings = pd.read_csv(path + \"ml-latest-small/ratings.csv\")\n\telif dataset_type == \"full\":\n\t\tmovies = pd.read_csv(path + \"ml-latest/movies.csv\")\n\t\tratings = pd.read_csv(path + \"ml-latest/ratings.csv\")\n\treturn movies, ratings\n\n# Preprocessing data\n\n# Delete films seen only by a certain number of users\ndef get_id_delete_solo_films(data, threshold, nom_colonne) :\n '''\n data -> movies ou ratings ( dataframe qui contient une colonne movieId )\n '''\n list_key_values = np.array(list(Counter(data[nom_colonne].values).items()))\n key,values = list_key_values[:,0],list_key_values[:,1]\n id_delete = np.where(values < threshold)[0]\n return key[id_delete]\n\ndef delete_solo_films(data,id_delete,nom_colonne) :\n '''\n data -> movies ou ratings ( dataframe qui contient une colonne movieId )\n '''\n array_movieId = data[nom_colonne].values\n ind = [i for i in range(len(array_movieId)) if array_movieId[i] not in id_delete ]\n return data.iloc[ind]\n\n# Building ratings and movies dataframe which both contains the same movieId\ndef clear_dataset(movies, ratings):\n\n\tid_delete = get_id_delete_solo_films(ratings, MINIMUM_SEEN_MOVIES,'movieId')\n\tratings = delete_solo_films(ratings,id_delete,'movieId')\n\tmovies = delete_solo_films(movies,id_delete,'movieId')\n\tid_delete = get_id_delete_solo_films(ratings, MINIMUM_SEEN_USERS,'userId')\n\tratings = delete_solo_films(ratings,id_delete,'userId')\n\t\n\tlist_movieId = list(set(movies[\"movieId\"].values).intersection(set(ratings[\"movieId\"].values)))\n\tmovies_old = movies['movieId'].values\n\tl = []\n\tfor i in range(len(movies_old)):\n\t\tif movies_old[i] in list_movieId:\n\t\t\tl.append(i)\n\tmovies = movies.iloc[l,:]\n\n\ta = sorted(list(list_movieId))\n\tb = range(len(a))\n\td = dict(zip(a,b))\n\tmovies = movies.replace({'movieId' : d})\n\n\ta = sorted(list(list_movieId))\n\tb = range(len(a))\n\td = dict(zip(a,b))\n\tratings = ratings.replace({'movieId' : d})\n \n\tratings.index = range(len(ratings))\n\tmovies.index = range(len(movies))\n\n\treturn movies, ratings\n\n# Building one hot encoded genres in movies dataframe\ndef one_hot_encode_genres(movies):\n\ttmp = []\n\tfor elt in movies[\"genres\"]:\n\t\ttmp.append(elt.split(\"|\"))\n\tmovies[\"genres\"] = tmp\n\tmlb = MultiLabelBinarizer(sparse_output=True)\n\tmovies = movies.join(\n\t\t\t\tpd.DataFrame.sparse.from_spmatrix(\n\t\t\t\t\t\t\t\t\t\t\t\tmlb.fit_transform(movies.pop('genres')),\n\t\t\t\t\t\t\t\t\t\t\t\tindex=movies.index,\n\t\t\t\t\t\t\t\t\t\t\t\tcolumns=mlb.classes_))\n\treturn movies\n\n# Cleaning ratings datagrame\ndef preprocess_ratings(ratings):\n\tratings = ratings.drop(columns=[\"timestamp\"])\n\tratings['userId'] = ratings['userId'].to_numpy() - 1 # car pas de user 0\n\treturn ratings\n\n# Split for computing metrics on test later\ndef split_set(userId, train_size, ratings):\n\trating_user = ratings[ratings[\"userId\"] == userId]\n\ttrain_rating_user, test_rating_user = rating_user.to_numpy()[:int(train_size*len(rating_user))], rating_user.to_numpy()[int(train_size*len(rating_user)):]\n\treturn train_rating_user, test_rating_user\n\n# Get informations on users watched/unwatched movies...\ndef get_infos_user(userId, ratings):\n\twatched_user = set(ratings[ratings[\"userId\"] == userId][\"movieId\"])\n\twatched_all = set(ratings['movieId'])\n\tunwatched_user = list(watched_all.difference(watched_user))\n\treturn watched_user, watched_all, unwatched_user\n\n# Building matrix\n\n# Building a matrix M = (n_movies, n_movies) which contains the number of users who'se seen m_i and m_j\ndef build_M_matrix(ratings, train_size):\n\tdata_dict = dict()\n\ttrain_rating_user_list = []\n\ttest_rating_user_list = []\n\tfor userId in tqdm(set(ratings[\"userId\"])):\n\t\ttrain_rating_user, test_rating_user = split_set(userId, train_size, ratings)\n\t\ttrain_rating_user_list.append(np.array(train_rating_user))\n\t\ttest_rating_user_list.append(np.array(test_rating_user))\n\t\titerator = it.combinations(train_rating_user[:,1], 2)\n\t\tfor x, y in iterator:\n\t\t\tdata_dict[(x,y)] = data_dict.get((x,y), 0.) + 1.\n\t\t\tdata_dict[(y,x)] = data_dict.get((y,x), 0.) + 1.\n\t\titerator = it.combinations(test_rating_user[:,1], 2)\n\t\tfor x, y in iterator:\n\t\t\t# We need to ignore the test movies\n\t\t\tdata_dict[(x,y)] = 0\n\t\t\tdata_dict[(y,x)] = 0\n\tkeys = np.array(list(data_dict.keys())).astype(int)\n\tvalues = np.array(list(data_dict.values())).astype(float)\n\tM_coo = scipy.sparse.coo_matrix((values, (keys[:,0], keys[:,1])))\n\tM_csr = M_coo.tocsr()\n\tM_norm = M_csr\n\treturn M_norm, train_rating_user_list, test_rating_user_list\n\n# Computing probabilites of genres P_ig\ndef build_P_ig(movies):\n\tsum_ = movies[[i for i in movies.columns if i != \"movieId\" and i != \"title\"]].to_numpy().sum(axis=0).astype(int)\n\tP_ig = sum_ / sum(sum_)\n\treturn P_ig.reshape(-1, 1)\n\n# Initialisation of R_uk before iterative algorithm\ndef init_R_uk(movies):\n\tn_genres = len(movies.columns) - 2\n\tn_movies = len(movies)\n\tr = 1/(n_movies*n_genres)\n\tR_uk = np.full((n_movies, n_genres), r)\n\treturn R_uk\n\n# Computing F_ig for each user\ndef build_F_ig(R_uk, P_ig):\n\tF_ig = np.sum(R_uk, axis=1).reshape(-1,1) @ P_ig.reshape(1,-1)\n\treturn F_ig\n\n# Matrix user X movie\ndef build_ratings_matrix(ratings):\n\tvalues = ratings[\"rating\"]\n\trows = ratings[\"userId\"]\n\tcols = ratings[\"movieId\"]\n\tM_coo = scipy.sparse.coo_matrix((values, (rows, cols)))\n\tM_csr = M_coo.tocsr()\n\treturn M_csr\n\n# Build I_uk for each user\ndef build_I_uk(tmp_M, id_user, P_ig):\n\tI_uk = tmp_M[id_user,:].T @ P_ig.reshape(1,-1)\n\tI_uk = I_uk / I_uk.sum(axis=0).T\n\treturn I_uk\n\n# Init the matrix needed before running the iterative algorithm\ndef init(movies, ratings, train_size):\n\tprint(\"Init R_uk...\")\n\tR_uk = init_R_uk(movies)\n\tprint(R_uk.shape)\n\tprint(\"Building P_ig...\")\n\ttmp_M = build_ratings_matrix(ratings)\n\tP_ig = build_P_ig(movies)\n\tprint(P_ig.shape)\n\tprint(\"Building M_csr...\")\n\tM_csr, train_rating_user_list, test_rating_user_list = build_M_matrix(ratings, train_size)\n\tprint(M_csr.shape)\n\treturn R_uk, tmp_M, P_ig, M_csr, np.array(train_rating_user_list, dtype=object), np.array(test_rating_user_list, dtype=object)\n\n# Run the algorithm\n\n# Compute TR_ki for a specific user\ndef compute_TR_ki(id_user, R_uk, tmp_M, P_ig, M_csr, d, alpha, iter_max):\n\tI_uk = build_I_uk(tmp_M, id_user, P_ig)\n\tfor _ in range(iter_max):\n\t\tF_ig = build_F_ig(R_uk, P_ig)\n\t\tR_uk = d * alpha * M_csr @ R_uk + d * (1-alpha) * M_csr @ F_ig + (1-d) * I_uk\n\n\t\t# This part is useful if you want to normalize + break if converge\n\t\t# R_uk = (R_uk / R_uk.sum(axis=1)).T # Normalization isn't working\n\t\t# print(np.abs(np.sum(R_uk - R_uk_old)))\n\t\t# if np.abs(np.sum(R_uk - R_uk_old)) < eps :\n\t\t# print(i)\n\t\t# break\n\t\t# R_uk_old = R_uk.copy()\n\t\n\tTR_ki = np.array(R_uk @ P_ig) # It returns a np.mat object which can't be reduced to dimension 1\n\treturn TR_ki.reshape(-1)\n\n# Compute TR_ki for all users\ndef iterative_TR_ki(n_user, R_uk, tmp_M, P_ig, M_csr, d=0.15, alpha=0.1, iter_max=5):\n\tprint(\"Computing TR_ki for all users...\")\n\tTR_ki_all_user = []\n\tfor id_user in tqdm(range(n_user)):\n\t\tTR_ki_all_user.append(compute_TR_ki(id_user, R_uk, tmp_M, P_ig, M_csr, d, alpha, iter_max))\n\treturn np.array(TR_ki_all_user)\n\n# Running some test for a test user\n\n# Returns the recommandation for the users\ndef sort_by_best_movie(TR_ki_all_user):\n\tsorted_movies_all_user = np.zeros_like(TR_ki_all_user)\n\tfor i in range(len(TR_ki_all_user)):\n\t\tsorted_movies_all_user[i,:] = np.argsort(TR_ki_all_user[i,:])[::-1]\n\treturn sorted_movies_all_user\n\n","repo_name":"hanzopgp/PageRankRecommandation","sub_path":"src/final_project/topic_page_rank.py","file_name":"topic_page_rank.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"15789153581","text":"\"\"\"\nMy security stuff is in my local setting \n\"\"\"\nfrom pathlib import Path\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\nDEBUG = True\n\nALLOWED_HOSTS = []\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\n\n\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'django-insecure--5^aqetj=sk^7)4x##)zc^+3j&7=wnrp%c25t-=!)lpguw8nx)'\n","repo_name":"Abyys001/play-and-practice","sub_path":"django/news_site/news_site/local_setting.py","file_name":"local_setting.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12148225228","text":"'''\ndef countdown(n):\n if n <= 0:\n print('Blastofffactorial')\n else:\n print(n)\n countdown(n-1)\n\ncountdown(3)\n\ndef print_n(s, n):\n if n <= 0:\n return\n print(s)\n print('n = ', n)\n print_n(s, n-1)\n\nprint_n('Hello', 3)\n\n# for recursion: needs ending point and something to get there\n'''\ndef factorial(x):\n if x == 1:\n return 1 \n print('curent x = ', x)\n return x * factorial(x-1)\n\nprint(factorial(7))\n\ndef fib(n):\n if n == 1 or n == 2:\n return 1\n return fib(n-1) + fib(n-2)\n\nprint(fib(3))\nprint(fib(10))","repo_name":"sokjunem/MIS3640","sub_path":"Session/session6_recursion_demo.py","file_name":"session6_recursion_demo.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"38939646071","text":"import numpy as np\nimport pandas as pd\n\nx_cols = [\n \"AGE\",\n \"ALBUMIN_TX\",\n \"ASCITES_TX\",\n \"BACT_PERIT_TCR\",\n \"BMI_DON_CALC\",\n \"CITIZENSHIP\",\n \"CMV_STATUS\",\n \"CREAT_TX\",\n \"DAYSWAIT_CHRON\",\n \"DGN2_TCR2\",\n \"DGN_TCR1\",\n \"DIAL_TX\",\n \"EBV_SEROSTATUS\",\n \"EDUCATION\",\n \"ENCEPH_TX\",\n \"ETHCAT\",\n \"ETHNICITY\",\n \"EVER_APPROVED\",\n \"EXC_CASE\",\n \"EXC_DIAG_ID\",\n \"EXC_HCC\",\n \"FINAL_INR\",\n \"FINAL_SERUM_SODIUM\",\n \"FUNC_STAT_TCR\",\n \"FUNC_STAT_TRR\",\n \"GENDER\",\n \"HBV_CORE\",\n \"HBV_SUR_ANTIGEN\",\n \"HCC_DIAG\",\n \"HCC_DIAGNOSIS_TCR\",\n \"HCC_EVER_APPR\",\n \"HCV_SEROSTATUS\",\n \"HGT_CM_CALC\",\n \"HGT_CM_TCR\",\n \"HIV_SEROSTATUS\",\n \"INIT_ALBUMIN\",\n \"INIT_ASCITES\",\n \"INIT_BILIRUBIN\",\n \"INIT_BMI_CALC\",\n \"INIT_DIALYSIS_PRIOR_WEEK\",\n \"INIT_ENCEPH\",\n \"INIT_INR\",\n \"INIT_MELD_PELD_LAB_SCORE\",\n \"INIT_SERUM_CREAT\",\n \"INIT_SERUM_SODIUM\",\n \"INIT_WGT_KG\",\n \"INR_TX\",\n \"LIFE_SUP_TCR\",\n \"LIFE_SUP_TRR\",\n \"MALIG_TCR\",\n \"MALIG_TRR\",\n \"MED_COND_TRR\",\n \"MELD_PELD_LAB_SCORE\",\n \"NUM_PREV_TX\",\n \"ON_VENT_TRR\",\n \"PORTAL_VEIN_TCR\",\n \"PORTAL_VEIN_TRR\",\n \"PREV_AB_SURG_TCR\",\n \"PREV_AB_SURG_TRR\",\n \"PREV_TX\",\n \"TBILI_TX\",\n \"TIPSS_TCR\",\n \"TIPSS_TRR\",\n \"VENTILATOR_TCR\",\n \"WGT_KG_CALC\",\n \"WORK_INCOME_TCR\",\n \"WORK_INCOME_TRR\",\n \"abo\",\n \"cancer\",\n \"diabbin\",\n \"diag1\",\n \"hosptime\",\n \"insdiab\",\n \"meldstat\",\n \"meldstatinit\",\n \"status1\",\n \"statushcc\",\n]\n\no_cols = [\n \"AGE_DON\",\n \"ALCOHOL_HEAVY_DON\",\n \"ANTIHYPE_DON\",\n \"ARGININE_DON\",\n \"BLOOD_INF_DON\",\n \"BMI_DON_CALC\",\n \"BUN_DON\",\n \"CARDARREST_NEURO\",\n \"CDC_RISK_HIV_DON\",\n \"CITIZENSHIP_DON\",\n \"CLIN_INFECT_DON\",\n \"CMV_DON\",\n \"COD_CAD_DON\",\n \"CREAT_DON\",\n \"DDAVP_DON\",\n \"DIABETES_DON\",\n \"EBV_IGG_CAD_DON\",\n \"EBV_IGM_CAD_DON\",\n \"ETHCAT_DON\",\n \"GENDER_DON\",\n \"HBSAB_DON\",\n \"HBV_CORE_DON\",\n \"HEMATOCRIT_DON\",\n \"HEPARIN_DON\",\n \"HEP_C_ANTI_DON\",\n \"HGT_CM_DON_CALC\",\n \"HISTORY_MI_DON\",\n \"HIST_CANCER_DON\",\n \"HIST_CIG_DON\",\n \"HIST_COCAINE_DON\",\n \"HIST_HYPERTENS_DON\",\n \"HIST_INSULIN_DEP_DON\",\n \"HIST_OTH_DRUG_DON\",\n \"INOTROP_SUPPORT_DON\",\n \"INSULIN_DON\",\n \"INTRACRANIAL_CANCER_DON\",\n \"NON_HRT_DON\",\n \"PH_DON\",\n \"PREV_TX_ANY\",\n \"PROTEIN_URINE\",\n \"PT_DIURETICS_DON\",\n \"PT_STEROIDS_DON\",\n \"PT_T3_DON\",\n \"PT_T4_DON\",\n \"PULM_INF_DON\",\n \"RECOV_OUT_US\",\n \"RESUSCIT_DUR\",\n \"SGOT_DON\",\n \"SGPT_DON\",\n \"SKIN_CANCER_DON\",\n \"TATTOOS\",\n \"TBILI_DON\",\n \"TRANSFUS_TERM_DON\",\n \"URINE_INF_DON\",\n \"VASODIL_DON\",\n \"VDRL_DON\",\n \"WGT_KG_DON_CALC\",\n \"abodon\",\n \"coronary\",\n \"death_mech_don_group\",\n \"deathcirc\",\n \"dontime\",\n \"macro\",\n \"micro\",\n]\n\n\nx_cols_unos_ukeld = [\n \"diag1\", #'PRIMARY_LIVER_DISEASE' TODO: see corresponding with UKReg (same codes)\n \"AGE\", #'reg_age'\n \"GENDER\", #'SEX'\n \"INIT_SERUM_CREAT\", #'SERUM_CREATININE'\n \"INIT_BILIRUBIN\", #'SERUM_BILIRUBIN'\n \"INIT_INR\", #'INR'\n \"INIT_SERUM_SODIUM\", #'SERUM_SODIUM'\n \"INIT_DIALYSIS_PRIOR_WEEK\",\n \"DIAL_TX\", #'RENAL_SUPPORT', 'RREN_SUP'\n \"MED_COND_TRR\", #'PATIENT_LOCATION' TODO: check whether variables correspond to UKReg\n \"LISTYR\", #'regyr'\n # , #'outcome'\n # , #'RCSPLD1' -> diag1 (above)\n # , #'RAGE'\n # , #'RSEX'\n \"HCV_SEROSTATUS\", #'RHCV'\n \"CREAT_TX\", #'RCREAT'\n \"TBILI_TX\", #'RBILIRUBIN'\n \"FINAL_INR\", #'RINR'\n \"FINAL_SERUM_SODIUM\", #'RSODIUM'\n # , #'RPOTASSIUM' -> not in UNOS\n \"INIT_ALBUMIN\", #'RALBUMIN'\n #'PREV_AB_SURG_TCR',\n \"PREV_AB_SURG_TRR\", #'RAB_SURGERY'\n \"INIT_ENCEPH\", #'RENCEPH'\n #'INIT_ASCITES',\n \"ASCITES_TX\", #'RASCITES' TODO: this is categorical in UNOS, see how this corresponds to UKReg\n # , #'PSURV'\n]\n\no_cols_unos_ukeld = [\n \"AGE_DON\", #'DAGE'\n #'death_mech_don_group', 'deathcirc', #'DCOD' -> TODO: these may vary significantly from UKReg, best to check\n \"BMI_DON_CALC\", #'DBMI'\n \"NON_HRT_DON\", #'DGRP' -> in UNOS 'NON_HRT_DON' distinguishes between dead donors and circulatory death donors;\n # Living are excluded for now. TODO: check wether codes correspond to UKReg\n]\n\nUNOS_2_UKReg_mapping = {\n \"AGE\": \"RAGE\",\n \"AGE_DON\": \"DAGE\",\n \"ASCITES_TX\": \"RASCITES\", # TODO: merge\n \"BMI_DON_CALC\": \"DBMI\",\n \"CREAT_TX\": \"RCREAT\",\n \"DIAL_TX\": \"RREN_SUP\", # , RREN_SUP TODO: merge\n \"FINAL_INR\": \"RINR\",\n \"FINAL_SERUM_SODIUM\": \"RSODIUM\",\n \"GENDER\": \"SEX\",\n \"HCV_SEROSTATUS\": \"RHCV\",\n \"INIT_ALBUMIN\": \"RALBUMIN\",\n #'INIT_ASCITES': 'RASCITES', # TODO: merge\n \"INIT_BILIRUBIN\": \"SERUM_BILIRUBIN\",\n \"INIT_DIALYSIS_PRIOR_WEEK\": \"RENAL_SUPPORT\", # , RREN_SUP TODO: merge\n \"INIT_ENCEPH\": \"RENCEPH\",\n \"INIT_INR\": \"INR\",\n \"INIT_SERUM_CREAT\": \"SERUM_CREATININE\",\n \"INIT_SERUM_SODIUM\": \"SERUM_SODIUM\",\n \"LISTYR\": \"regyr\",\n \"MED_COND_TRR\": \"PATIENT_LOCATION\",\n \"NON_HRT_DON\": \"DGRP\",\n #'PREV_AB_SURG_TCR': 'RAB_SURGERY', # TODO: merge\n \"PREV_AB_SURG_TRR\": \"RAB_SURGERY\", # TODO: merge\n \"PTIME\": \"rwtime\",\n \"TBILI_TX\": \"RBILIRUBIN\",\n #'death_mech_don_group': 'DCOD', # TODO: merge\n #'deathcirc': 'DCOD', # TODO: merge\n \"diag1\": \"PRIMARY_LIVER_DISEASE\",\n \"PSTATUS\": \"CENS\",\n}\n\n\ndef get_data_tuples(location: str) -> tuple:\n # Divide data in tuples as described in the paper.\n\n # LOAD\n liver_train = pd.read_csv(f\"{location}/liver_processed_train.csv\")\n liver_test = pd.read_csv(f\"{location}/liver_processed_test.csv\")\n\n # ONLY USE PRESENT COLS\n x_cols_intersected = np.intersect1d(liver_train.columns.values, x_cols)\n o_cols_intersected = np.intersect1d(liver_train.columns.values, o_cols)\n\n # SPLIT FILE IN PATIENTS (X), ORGANS (O), OUTCOME (Y), CENSOR (del)\n X_train = liver_train[x_cols_intersected]\n O_train = liver_train[o_cols_intersected]\n Y_train = liver_train[[\"PTIME\"]]\n del_train = liver_train[[\"PSTATUS\"]] - 1 # PSTATUS is a censor variable\n\n X_test = liver_test[x_cols_intersected]\n O_test = liver_test[o_cols_intersected]\n Y_test = liver_test[[\"PTIME\"]]\n del_test = liver_test[[\"PSTATUS\"]] - 1\n\n return X_train, O_train, Y_train, del_train, X_test, O_test, Y_test, del_test\n","repo_name":"jeroenbe/organsync","sub_path":"src/organsync/experiments/data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"72015470359","text":"import pytux.util as util\nimport pytux.log.log as log\nimport pytux.log.core as core\n\n\n__tasks_log = {\n \"show\": core.show,\n \"clear\": core.clear\n}\n\n\ndef main(argv):\n \"\"\"\n Entry point of `pytux log` command.\n\n :param argv: command line arguments passed to tasks.\n :return: 0 on success, -1 on error.\n \"\"\"\n try:\n msg = __tasks_log[argv.task](argv)\n if msg is not None:\n util.print_err_msg(msg)\n return -1\n except Exception as err:\n util.print_err_msg(log.get_err_tb(err))\n return -1\n return 0\n","repo_name":"zhenyatos/pytux","sub_path":"pytux/log/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32581378983","text":"import autocorelatie\nimport spectograma\nimport cepstrum\nimport knn\nimport kmeans\nimport os\n#from cauta_csv import cauta_csv\n\ndef procesare(path_folder_note, path_rezultat):\n print(\"\\nAti ales sa faceti procesare pe {} \"\n \"\\nsi sa returnati {}.\".format(path_folder_note, path_rezultat))\n\n tipuri = [None, 'autocorelatie', 'spectograma', 'cepstrum']\n raspuns = int(input(\"\\nTip procesare dorit: autocorelatie(1), spectograma(2), cepstrum(3) sau skip procesare(0). \"))\n\n if raspuns:\n print(\"\\nPentru procesare, ati ales: {}.\".format(tipuri[raspuns]) + \"\\nSe proceseaza...\")\n\n functie = tipuri[raspuns] + '.procesare(path_folder_note, path_rezultat)'\n eval(functie)\n\n return 0\n\n\ndef recunoastere(path_rezultat):\n print(\"\\nAti ales sa faceti recunoastere pe {}.\".format(path_rezultat))\n\n tipuri = [None, 'knn', 'kmeans']\n raspuns = int(input(\"\\nTip machine learning algorithm dorit: k-nn(1), k-means(2) sau skip ML(0). \"))\n\n if raspuns:\n print(\"\\nPentru recunoastere, ati ales: {}.\".format(tipuri[raspuns]) + \"\\nSe clasifica...\")\n\n functie = tipuri[raspuns] + '.recunoastere(path_rezultat)'\n eval(functie)\n\n return 0\n\n\nif __name__ == '__main__':\n path_proiect = os.getcwd()\n\n # Rezultatul poate fi:\n # autocorelatie: test1.csv (ex.: autocor_test_filtrate.csv)\n # spectograma: test1 (ex.: spectograme_train_filtrate)\n folder_note = 'note_trainsitest'\n rezultat_procesare = 'autocor_trainsitest.csv'\n\n path_folder_note = r'{}'.format(os.path.join(os.getcwd(), folder_note))\n path_rezultat = r'{}'.format(os.path.join(os.getcwd(), rezultat_procesare))\n\n procesare(path_folder_note, path_rezultat)\n recunoastere(path_rezultat)\n\n # 17 gresite in train + 14 gresite in test\n # 21 gresite in train_filtrate + 15 gresite in test\n","repo_name":"andreeagunea/Notes-Recognition","sub_path":"procesare/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26142764615","text":"\"\"\"\nThis module contains some useful classes and functions to deal with RDF data and\nread and process XML files.\n\"\"\"\n\nfrom nltk.tokenize import word_tokenize\nimport xml.etree.ElementTree as et\nfrom collections import defaultdict\nimport argparse\nimport os\n\n\nclass Triple:\n\n def __init__(self, s, p, o):\n self.subject = s\n self.object = o\n self.property = p\n\n\nclass Tripleset:\n\n def __init__(self):\n self.triples = []\n\n def fill_tripleset(self, t):\n for xml_triple in t:\n s, p, o = xml_triple.text.split(' | ')\n\n # inistiate a triple\n triple = Triple(s, p, o)\n self.triples.append(triple)\n\n\nclass Lexicalisation:\n\n def __init__(self, lex, comment, lid):\n self.lex = lex\n self.comment = comment\n self.id = lid\n\n\nclass Entry:\n\n def __init__(self, category, size, eid):\n self.originaltripleset = []\n self.modifiedtripleset = Tripleset()\n self.lexs = []\n self.category = category\n self.size = size\n self.id = eid\n\n def fill_originaltriple(self, xml_t):\n otripleset = Tripleset()\n self.originaltripleset.append(otripleset) # multiple originaltriplesets for one entry\n otripleset.fill_tripleset(xml_t)\n\n def fill_modifiedtriple(self, xml_t):\n self.modifiedtripleset.fill_tripleset(xml_t)\n\n def create_lex(self, xml_lex):\n comment = xml_lex.attrib['comment']\n lid = xml_lex.attrib['lid']\n lex = Lexicalisation(xml_lex.text, comment, lid)\n self.lexs.append(lex)\n\n def count_lexs(self):\n return len(self.lexs)\n\n\nclass RDFInstance(object):\n\n def __init__(self, category, size, otripleset, mtripleset, lex=None):\n \"\"\"\n Instantiate RDFInstance object.\n :param category: category of entry (dtype: string)\n :param size: number of triples in entry (dtype: int)\n :param otripleset: a list original tripleset (dtype: list (Tripleset))\n :param mtripleset: a modified tripleset (dtype: Tripleset)\n :param sentence: a sentence that realises the triple set for training\n instances\n :dtype: Lexicalisation object (to get text, Lexicalisation.lex)\n :default: None (for eval and test instances).\n \"\"\"\n\n self.category = category\n self.size = size\n self.originaltripleset = otripleset\n self.modifiedtripleset = mtripleset\n\n if lex:\n self.Lexicalisation = lex\n\n self.entities = set()\n self.properties = set()\n\n self._populate_sets()\n\n\n def _populate_sets(self):\n \"\"\"\n populate the two sets; entities and properties.\n \"\"\"\n for tset in self.originaltripleset:\n for triple in tset.triples:\n s = triple.subject\n p = triple.property\n o = triple.object\n\n self.entities.update((s, o))\n self.properties.add(p)\n\n\ndef parseXML(xml_file):\n \"\"\"\n Parse an xml file, return a list of RDF-Text instances (list(Entry)).\n :param category: xml_file string (dtype: string)\n \"\"\"\n\n entries = []\n\n tree = et.parse(xml_file)\n root = tree.getroot()\n\n for xml_entry in root.iter('entry'):\n # to ignore triples with no lexicalisations\n # get a list of tags in the entry\n tags = [c.tag for c in xml_entry]\n\n if \"lex\" not in tags:\n # skip this entry, move to next entry in the loop\n continue\n\n # get attributes\n entry_id = xml_entry.attrib['eid']\n category = xml_entry.attrib['category']\n size = xml_entry.attrib['size']\n\n entry = Entry(category, size, entry_id)\n\n for element in xml_entry:\n if element.tag == 'originaltripleset':\n entry.fill_originaltriple(element)\n elif element.tag == 'modifiedtripleset':\n entry.fill_modifiedtriple(element)\n elif element.tag == 'lex':\n entry.create_lex(element)\n\n entries.append(entry)\n\n return entries\n\n\ndef generate_instances(dir, extended=False, eval=False):\n \"\"\"\n Traverse through a path, visit all subdirectories, and return a dict of\n entries accessible by size: size --> list of entries\n :param dir: path to data files (dtype: string)\n :param extended: should it generate entities and properties?\n (dtype: bool, default: False)\n \"\"\"\n\n subfolders = [f.path for f in os.scandir(dir) if f.is_dir() ]\n\n instances = defaultdict(list)\n\n global_entities = set()\n global_properties = set()\n\n # loop through each dir\n for d in sorted(subfolders):\n xml_files = [f for f in os.listdir(d) if f.endswith('.xml')]\n\n # loop through each file in the directory\n for f in xml_files:\n # create new XMLParser object\n entries = parseXML(d + '/' + f)\n\n if eval:\n for entry in entries:\n rdfInstance = RDFInstance(entry.category,\n entry.size,\n entry.originaltripleset,\n entry.modifiedtripleset,\n entry.lexs)\n\n # append to list of instances\n instances[entry.size].append(rdfInstance)\n\n if extended:\n global_entities.update(rdfInstance.entities)\n global_properties.update(rdfInstance.properties)\n\n else:\n for entry in entries:\n for lex in entry.lexs:\n rdfInstance = RDFInstance(entry.category,\n entry.size,\n entry.originaltripleset,\n entry.modifiedtripleset,\n lex)\n\n # append to list of instances\n instances[entry.size].append(rdfInstance)\n\n if extended:\n global_entities.update(rdfInstance.entities)\n global_properties.update(rdfInstance.properties)\n\n return instances, global_entities, global_properties\n","repo_name":"badrex/rdf2text","sub_path":"utils/rdf_utils.py","file_name":"rdf_utils.py","file_ext":"py","file_size_in_byte":6286,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"85"} +{"seq_id":"37888302608","text":"class Solution:\n # @param num, a list of integers\n # @return a string\n def largestNumber(self, num):\n slist = []\n output = ''\n\n def comparator(a,b):\n ab = int(str(a)+str(b))\n ba = int(str(b)+str(a))\n return ab if ab > ba else ba\n\n\n for y in range(9,0,-1):\n matches = [x for x in num if str(x)[0] == str(y)]\n matches.sort(reverse=True)\n if not matches:\n continue\n if len(matches) == 1:\n output += str(matches[0])\n continue\n for m in range(0,len(matches)-1,2):\n output += str(comparator(matches[m],matches[m-1]))\n\n return output\n\n\n\ns = Solution()\ns.largestNumber([98,9, 91, 94])\ns.largestNumber([1,121])\ns.largestNumber([1])\ns.largestNumber([1,1,1])\n \n\n\n \n\n \n","repo_name":"staubhp/leetcode-solutions","sub_path":"largest-number.py","file_name":"largest-number.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"13228036792","text":"import tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import Model\nfrom offline.rank.models.layer import AttentionSequencePoolingLayer\nimport tensorflow.keras.backend as K\n\n\nclass Din(object):\n\n def __init__(self, user_num=4691, movie_num=2514, year_num=76, genre_num=9, embedding_size=16):\n self.user_num = user_num\n self.movie_num = movie_num\n self.year_num = year_num\n self.genre_num = genre_num\n self.embedding_size = embedding_size\n\n self.inputs = self.get_inputs()\n self.get_embedding()\n\n def get_inputs(self):\n \"\"\"\n 输入\n :return:\n \"\"\"\n self.user_id_in = Input(shape=(1,), name=\"user_id\", dtype=tf.int64)\n self.user_recent_click_movie_ids_in = Input(shape=(20,), name=\"user_recent_click_movie_ids\", dtype=tf.int64)\n self.user_recent_click_labels_in = Input(shape=(20,), name=\"user_recent_click_labels\", dtype=tf.int64)\n self.user_like_genres_in = Input(shape=(2,), name=\"user_like_genres\", dtype=tf.int64)\n\n self.movie_id_in = Input(shape=(1,), name=\"movie_id\", dtype=tf.int64)\n self.current_label_in = Input(shape=(1,), name=\"current_label\", dtype=tf.int64)\n self.release_year_in = Input(shape=(1,), name=\"release_year\", dtype=tf.int64)\n\n return [self.user_id_in, self.user_recent_click_movie_ids_in, self.user_recent_click_labels_in, \\\n self.user_like_genres_in, self.movie_id_in, self.current_label_in, self.release_year_in]\n\n def get_embedding(self):\n self.user_embedding = Embedding(self.user_num, self.embedding_size)\n self.movie_embedding = Embedding(self.movie_num, self.embedding_size)\n self.genre_embedding = Embedding(self.genre_num, self.embedding_size)\n self.year_embedding = Embedding(self.year_num, self.embedding_size)\n\n def get_attention_vector(self):\n movie = self.movie_embedding(self.movie_id_in)\n genre = self.genre_embedding(self.current_label_in)\n\n hist_movies = self.movie_embedding(self.user_recent_click_movie_ids_in)\n hist_genres = self.genre_embedding(self.user_recent_click_labels_in)\n\n q = Concatenate()([movie, genre])\n k = Concatenate()([hist_movies, hist_genres])\n\n x = AttentionSequencePoolingLayer()([q, k])\n\n x = Flatten()(x)\n\n return x\n\n def get_dense_vector(self):\n user = self.user_embedding(self.user_id_in)\n user_genre = self.genre_embedding(self.user_like_genres_in)\n user_genre = Lambda(lambda x: tf.reduce_mean(x, axis=1, keepdims=True))(user_genre)\n movie = self.movie_embedding(self.movie_id_in)\n genre = self.genre_embedding(self.current_label_in)\n year = self.year_embedding(self.release_year_in)\n\n x = Concatenate()([user, user_genre, movie, genre, year])\n\n x = Flatten()(x)\n\n return x\n\n def mlp(self):\n attention_vector = self.get_attention_vector()\n dense_vector = self.get_dense_vector()\n\n x = Concatenate()([attention_vector, dense_vector])\n\n x = Dense(128, activation=\"relu\")(x)\n\n x = Dense(64, activation=\"relu\")(x)\n\n outputs = Dense(1, activation=\"sigmoid\")(x)\n\n return outputs\n\n def get_din_model(self):\n outputs = self.mlp()\n\n model = Model(inputs=self.inputs, outputs=outputs)\n\n return model\n","repo_name":"nicaibutou1993/ZimuRecSys","sub_path":"offline/rank/models/din.py","file_name":"din.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23491376711","text":"import os\nimport maya.cmds as cmds\n\nimport tank\nfrom tank import Hook\nfrom tank import TankError\n\nclass ScanSceneHook(Hook):\n \"\"\"\n Hook to scan scene for items to publish\n \"\"\"\n \n def execute(self, **kwargs):\n \"\"\"\n Main hook entry point\n :returns: A list of any items that were found to be published. \n Each item in the list should be a dictionary containing \n the following keys:\n {\n type: String\n This should match a scene_item_type defined in\n one of the outputs in the configuration and is \n used to determine the outputs that should be \n published for the item\n \n name: String\n Name to use for the item in the UI\n \n description: String\n Description of the item to use in the UI\n \n selected: Bool\n Initial selected state of item in the UI. \n Items are selected by default.\n \n required: Bool\n Required state of item in the UI. If True then\n item will not be deselectable. Items are not\n required by default.\n \n other_params: Dictionary\n Optional dictionary that will be passed to the\n pre-publish and publish hooks\n }\n \"\"\" \n \n items = []\n \n # get the main scene:\n scene_name = cmds.file(query=True, sn=True)\n if not scene_name:\n raise TankError(\"Please Save your file before Publishing\")\n \n scene_path = os.path.abspath(scene_name)\n scene_basename = os.path.basename(scene_path)\n\n # create the primary item - this will match the primary output 'scene_item_type': \n items.append({\"type\": \"work_file\", \"name\": scene_basename})\n \n # create the secondary output - add any wip renders found\n self._add_render_files(scene_path, items)\n \n return items\n \n def _add_render_files(self, path, items):\n \"\"\"\n Adds the wip render files on disk associated with this maya scene\n \"\"\"\n tk = tank.sgtk_from_path(path)\n template = tk.template_from_path(path)\n ctx = tk.context_from_path(path)\n \n fields = template.get_fields(path)\n version = fields[\"version\"]\n name = fields[\"name\"]\n \n # get the wip render files path\n if ctx.entity[\"type\"] == \"Asset\":\n type = fields[\"sg_asset_type\"]\n asset = fields[\"Asset\"]\n maya_asset_render = tk.templates[\"maya_asset_render\"]\n wip_renders = tk.paths_from_template(maya_asset_render, {\"sg_asset_type\": type, \"Asset\": asset, \"name\": name, \"version\": version})\n elif ctx.entity[\"type\"] == \"Shot\":\n spot = fields[\"Sequence\"]\n shot = fields[\"Shot\"]\n maya_shot_render = tk.templates[\"maya_shot_render\"]\n wip_renders = tk.paths_from_template(maya_shot_render, {\"Sequence\": spot, \"Shot\": shot, \"name\": name, \"version\": version})\n \n if wip_renders:\n wip_render_path = wip_renders[0]\n render_files = [name for name in os.listdir(wip_render_path)]\n baseFilename = \"\"\n for filename in render_files:\n newBaseFilename = filename.split('.')[0]\n if baseFilename != newBaseFilename:\n items.append({\"name\": newBaseFilename,\n \"type\": \"render_file\",\n \"description\":filename,\n \"other_params\": {\"source_folder\": wip_render_path,\n \"scene_path\": path}})\n \n baseFilename = newBaseFilename\n \n","repo_name":"AardmanCGI/aardtemplate","sub_path":"hooks/scan_scene_mayaRenders.py","file_name":"scan_scene_mayaRenders.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"7960406095","text":"#!/home/shino/.anyenv/envs/pyenv/shims/python\nimport sys\nfrom collections import Counter\n\nn = int(input())\nans = 10 ** 10\n\nfor i in range(1, n+1):\n b = n//i\n tmp = abs(i-b) + n-i*b\n ans = min(ans, tmp)\n\nprint(ans)\n","repo_name":"shinobe179/atcoder","sub_path":"abc040/b/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"21099340055","text":"import os\nimport xml.etree.ElementTree as ET\n\ndef changexml(xmlpath):\n xmllist = os.listdir(xmlpath)\n for c in xmllist:\n if os.path.splitext(c)[1] == '.xml':\n doc = ET.parse(os.path.join(xmlpath, c))\n root = doc.getroot()\n for s in root.findall('size'):\n s.find('depth').text = str(1)\n doc.write(os.path.join(xmlpath, c))\n\nif __name__ == \"__main__\":\n xmlpath = 'D:/jinkeloc/xml' # 存有xml的文件夹路径\n changexml(xmlpath)","repo_name":"manhongnie/imgpy","sub_path":"xmlmod.py","file_name":"xmlmod.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"810439988","text":"####### Package imports\nimport numpy as np\nimport networkx as nx\n\n##### Method to correctly read out the index of a tuple in a list\n##### ignoring the order of the elements\ndef redefined_index(list_of_tuples,element):\n \"\"\"redefine implemented index method for list \n \n Parameters\n ----------\n list_of_tuples : list\n A list containing tuples\n element : tuple\n A single tuple whose position in the list is calculated ignoring tuple orientation\n \n Returns\n -------\n integer \n index of element in list_of_tuples ignoring orientation of tuples\n \"\"\"\n \n assert isinstance(list_of_tuples,list)\n assert isinstance(element,tuple)\n \n try:\n index = list_of_tuples.index(element)\n except ValueError:\n index = list_of_tuples.index(element[::-1])\n return index\n\n########## Calculate PTDF matrix\ndef PTDF_matrix(G,I=np.array([])):\n \"\"\"Calculate Power Transfer Distribution Factor (PTDF) Matrix for power injections along graph's edges\n NOTE: This PTDF matrix is already multiplied from the right by the graphs \n incidence matrix, thus assuming power injections only to take place at the terminal\n ends of edges and resulting in a nof_edges x nof_edges matrix\n \n Parameters\n ---------- \n G : networkx graph\n Graph based on which Laplacian matrix and thus PTDF matrix is calulated\n I : (optional) numpy array\n Represents oriented edge node incidence matrix \n \n \n Returns\n -------\n numpy array\n Power Transfer Distribution Factor matrix of dimension number_of_edges x number_of_edges\n \"\"\"\n \n B = nx.laplacian_matrix(G).A\n if not I.size:\n I = nx.incidence_matrix(G,oriented=True).A\n\n edges = [(list(G.nodes()).index(u),list(G.nodes()).index(v)) for u,v in G.edges()]\n line_weights = np.array([B[e] for e in edges])\n B_d = -np.diag(line_weights)\n #multi_dot is supposed to find the most efficient way of performing the matrix multiplication\n #latter term is B inverse matrix\n try: \n #implicit matrix inversion\n B_inv = np.linalg.solve(B, I)\n PTDF_matrix = np.linalg.multi_dot([B_d,I.T,B_inv])\n ### This sometimes results in Singular Matrix error\n except np.linalg.LinAlgError:\n B_inv = np.linalg.pinv(B)\n PTDF_matrix = np.linalg.multi_dot([B_d,I.T,B_inv,I])\n return PTDF_matrix\n\n####\ndef shortest_edge_distance(G,e1,e2,weighted=False):\n \"\"\"Calculate the edge distance between edge e1 and edge e2 by taking the minimum of all\n shortest paths between the nodes\n \n Parameters\n ---------- \n G : weighted or unweighted networkx graph\n Graph in which distance is to be calculated\n e1, e2 : tuples \n Represent edges between which distance is to be calculated\n weighted : boolean\n If True, edge distance is calculated based on inverse edge weights\n \n Returns\n -------\n float \n The length of the shortest path between e1 and e2 in G\n \"\"\"\n\n assert isinstance(G,nx.Graph)\n assert isinstance(e1,tuple)\n assert isinstance(e2,tuple)\n \n possible_path_lengths = []\n F = G.copy()\n weight = nx.get_edge_attributes(F,'weight')\n if ((not len(weight)) or (not weighted)):\n weight = {e:1.0 for e in F.edges()}\n nx.set_edge_attributes(F,weight,'weight')\n inv_weight = {}\n for key in weight.keys():\n inv_weight[key] = 1/weight[key]\n nx.set_edge_attributes(F,inv_weight,'inv_weight')\n \n for i in range(2):\n for j in range(2):\n possible_path_lengths.append(nx.shortest_path_length(F,source=e1[i],target=e2[j],weight='inv_weight'))\n path_length = min(possible_path_lengths)+(F[e1[0]][e1[1]]['inv_weight']+F[e2[0]][e2[1]]['inv_weight'])/2\n return path_length \n\n##### Synthetic graphs model \ndef create_synthetic_ER_graphs(N1,N2,p1,p2,c1,c2,mu):\n \"\"\"Create two Erdös Renyi random graphs that are connected to\n each other at c1*N1 and c2*N2 vertices with probability mu\n \n Parameters\n ---------- \n N1, N2 : integers\n Parameter for number of nodes in ER graphs F and G\n p1, p2 : floats\n Parameters for connections probability in ER graphs\n c1, c2 : floats\n Parameter representing the share of nodes in F and G that potentially connect to each other\n mu : float\n connection probability for connections between F and G at nodes chosen by c1 and c2\n \n Returns\n -------\n networkx graph\n Result of the random connection of the two ER subgraphs with probability mu. \n Graph object contains two attributes accesible via G.graph['attribute']:\n 'connectors' contains a dictionary that, for each node in the graph, indicates\n whether the node is among the cN1 and cN2 nodes chosen \n as potentially connecting (value 1) or not (value 0)\n 'subgraph_nodes' contains a dictionary that for each node n indicates whether \n it belongs to the first subgraph (value 1) or \n second subgraph (value 0)\n \"\"\"\n\n #### Generate two ER random graphs\n G = nx.gnp_random_graph(n=N1,p=p1)\n F = nx.gnp_random_graph(n=N2,p=p1)\n \n #### Nodes of F and G are both named 1... N initally, so rename nodes of F in order to \n #### compose the graphs to a single large graph H\n mapping = {n:n+N1 for n in F.nodes()}\n F = nx.relabel_nodes(F,mapping=mapping)\n H = nx.compose(F,G)\n \n #### Now randomly choose int(c*N) nodes from both graphs that will connect to the other graph\n connectors_G = list(G.nodes())[:int(N1*c1)]\n connectors_F = list(F.nodes())[:int(N2*c2)]\n maximum_number_of_connections = len(connectors_G)*len(connectors_F)\n \n #### save connectors in node attributes \n nc = {n:0.0 for n in H.nodes()}\n for n in connectors_G:\n nc[n] = 1.0\n for n in connectors_F:\n nc[n] = 1.0\n nx.set_node_attributes(H,nc,'connectors')\n \n #### Save information about nodes belonging to subgraph G\n nodes_G = {n:0.0 for n in H.nodes()}\n for n in G.nodes():\n nodes_G[n] = 1.0\n nx.set_node_attributes(H,nodes_G,'subgraph_nodes')\n \n #### Set up variables to count the share of connections, in order to be able to compare it to mu\n current_number_of_connections = 0\n fraction_of_connections = 0\n \n ### now randomly add edges until required value of mu is reached\n while fraction_of_connections1:\n flag = True\n\n val = sum(board[x][y] for x,y in country)//len(country)\n for x,y in country:\n board[x][y] = val\n \n\n if(flag): count+=1\n else: break\nprint(count)\n\n","repo_name":"Geonjae-Joo/algorithm","sub_path":"baekjun/BFS/P16234/P16234.py","file_name":"P16234.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"35305428940","text":"\"\"\"\r\n/***************************************************************************\r\n Madeline_x.x.py\r\n\r\n Generator dokumentów oparty na szablonach i konfiguratorze.\r\n --------------------------------------\r\n Copyright: (C) 2022 by Piotr Michałowski\r\n Email: piotrm35@hotmail.com\r\n/***************************************************************************\r\n *\r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License version 2 as published\r\n * by the Free Software Foundation.\r\n *\r\n ***************************************************************************/\r\n\"\"\"\r\nSCRIPT_TITLE = 'Madeline'\r\nSCRIPT_VERSION = '1.2'\r\nGENERAL_INFO = u\"\"\"\r\nauthor: Piotr Michałowski, Olsztyn, woj. W-M, Poland\r\npiotrm35@hotmail.com\r\nwork begin: 03.10.2022\r\n\"\"\"\r\n\r\nimport os, sys, datetime\r\nimport codecs\r\nfrom PyQt5 import QtCore, QtWidgets, uic\r\nimport pyautogui\r\nfrom docx import Document # sudo pip3 install python-docx\r\nfrom lib.My_QLabel import My_QLabel\r\nfrom lib.DB_connection_PostgreSQL import DB_connection_PostgreSQL\r\nfrom lib.Text_filter import Text_filter\r\n\r\n# setup begin --------------------------------------\r\nDATABASE_USER = 'user_1'\r\n#---------------------------------------------------\r\nDOC_DATABASE_HOST = '127.0.0.1'\r\nDOC_DATABASE_PORT = '5432'\r\nDOC_DATABASE_NAME = 'documents'\r\n#---------------------------------------------------\r\nGGN_INFO_DATABASE_HOST = '127.0.0.1'\r\nGGN_INFO_DATABASE_PORT = '5432'\r\nGGN_INFO_DATABASE_NAME = 'ewid'\r\n# setup end ----------------------------------------\r\n\r\n\r\n#====================================================================================================================\r\n\r\n\r\nclass Madeline(QtWidgets.QMainWindow):\r\n\r\n\r\n def __init__(self):\r\n super(Madeline, self).__init__()\r\n self.DECYZJE_FOLDER_PATH = '.\\\\Decyzje'\r\n self.base_path = os.sep.join(os.path.realpath(__file__).split(os.sep)[0:-1])\r\n print(\"__init__, self.base_path = \" + str(self.base_path))\r\n uic.loadUi(os.path.join(self.base_path, 'ui', 'Madeline.ui'), self)\r\n self.setWindowTitle(SCRIPT_TITLE + ' v. ' + SCRIPT_VERSION)\r\n self.Nr_dokumentu_lineEdit.textChanged.connect(self.Nr_dokumentu_lineEdit_textChanged)\r\n self.Skladajacy_textEdit.textChanged.connect(self.Skladajacy_textEdit_textChanged)\r\n self.Zapisz_skladajacy_pushButton.clicked.connect(self.Zapisz_skladajacy_pushButton_clicked)\r\n self.Dzialajacy_checkBox.stateChanged.connect(self.Dzialajacy_checkBox_stateChanged)\r\n self.Inwestor_textEdit.textChanged.connect(self.Inwestor_textEdit_textChanged)\r\n self.Zapisz_inwestor_pushButton.clicked.connect(self.Zapisz_inwestor_pushButton_clicked)\r\n self.Numery_dzialek_textEdit.textChanged.connect(self.Numery_dzialek_textEdit_textChanged)\r\n self.Analizuj_pushButton.clicked.connect(self.Analizuj_pushButton_clicked)\r\n self.Przedmiot_textEdit.textChanged.connect(self.Przedmiot_textEdit_textChanged)\r\n self.Zapisz_przedmiot_pushButton.clicked.connect(self.Zapisz_przedmiot_pushButton_clicked)\r\n self.Csv_file_pushButton.clicked.connect(self.Csv_file_pushButton_clicked)\r\n self.Automat_pushButton.clicked.connect(self.Automat_pushButton_clicked)\r\n self.Generate_pushButton.clicked.connect(self.Generate_pushButton_clicked)\r\n self.Clear_pushButton.clicked.connect(self.Clear_pushButton_clicked)\r\n self.Prompt_pushButton.clicked.connect(self.Prompt_pushButton_clicked)\r\n self.Info_pushButton.clicked.connect(self.Info_pushButton_clicked)\r\n password = pyautogui.password(text='for ligin ' + DATABASE_USER + ':', title='DB password', default='', mask='*')\r\n self.DOC_dB_connection_PostgreSQL = DB_connection_PostgreSQL(DATABASE_USER, password, DOC_DATABASE_HOST, DOC_DATABASE_PORT, DOC_DATABASE_NAME)\r\n self.GGN_INFO_dB_connection_PostgreSQL = DB_connection_PostgreSQL(DATABASE_USER, password, GGN_INFO_DATABASE_HOST, GGN_INFO_DATABASE_PORT, GGN_INFO_DATABASE_NAME)\r\n self.text_filter = Text_filter()\r\n self.DOC_TEMPLATES_MAP = {\r\n 'Decyzja - TEMPLATE.docx': self.Decyzja_radioButton,\r\n 'Zgoda na przebudowę - TEMPLATE.docx': self.Zgoda_na_przebudowe_radioButton,\r\n 'Zezwolenie - TEMPLATE.docx': self.Zezwolenie_dr_wewn_radioButton,\r\n 'Uzgodnienie - TEMPLATE.docx': self.Uzgodnienie_radioButton,\r\n 'Uzgodnienie + SŁUŻEBNOŚĆ - TEMPLATE.docx': self.Uzgodnienie_i_sluz_przes_radioButton,\r\n 'Uzgodnienie + PRZEKAZANIE - TEMPLATE.docx': self.Uzgodnienie_i_przekazanie_radioButton,\r\n 'Uzgodnienie i opinia - TEMPLATE.docx': self.Uzgodnienie_i_opinia_radioButton,\r\n 'Uzgodnienie i opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx': self.Uzgodnienie_i_opinia_i_sluz_przes_radioButton,\r\n 'Uzgodnienie i opinia + PRZEKAZANIE - TEMPLATE.docx': self.Uzgodnienie_i_opinia_i_przekazanie_radioButton,\r\n 'Opinia - TEMPLATE.docx': self.Opinia_radioButton,\r\n 'Opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx': self.Opinia_i_sluz_przes_radioButton,\r\n 'Opinia + PRZEKAZANIE - TEMPLATE.docx': self.Opinia_i_przekazanie_radioButton,\r\n 'Pismo puste - TEMPLATE.docx': self.Pismo_puste_radioButton\r\n }\r\n self.DOC_TEMPLATES_NO_SENDER_LIST = [\r\n 'Uzgodnienie - TEMPLATE.docx',\r\n 'Uzgodnienie + SŁUŻEBNOŚĆ - TEMPLATE.docx',\r\n 'Uzgodnienie i opinia - TEMPLATE.docx',\r\n 'Uzgodnienie i opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx',\r\n 'Opinia - TEMPLATE.docx',\r\n 'Opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx'\r\n ]\r\n self.RODZAJ_MAP = {\r\n 'lokalizację': self.Lokalizacja_radioButton,\r\n 'budowę': self.Budowa_radioButton,\r\n 'przebudowę': self.Przebudowa_radioButton,\r\n 'remont': self.Remont_radioButton\r\n }\r\n self.parcel_select_sql_result = None\r\n self.automat_map = None\r\n self.numer_dokumentu_w_sprawie = 0\r\n \r\n \r\n def closeEvent(self, event): # overriding the method\r\n self.Nr_dokumentu_lineEdit.textChanged.disconnect(self.Nr_dokumentu_lineEdit_textChanged)\r\n self.Skladajacy_textEdit.textChanged.disconnect(self.Skladajacy_textEdit_textChanged)\r\n self.Zapisz_skladajacy_pushButton.clicked.disconnect(self.Zapisz_skladajacy_pushButton_clicked)\r\n self.Dzialajacy_checkBox.stateChanged.disconnect(self.Dzialajacy_checkBox_stateChanged)\r\n self.Inwestor_textEdit.textChanged.disconnect(self.Inwestor_textEdit_textChanged)\r\n self.Zapisz_inwestor_pushButton.clicked.disconnect(self.Zapisz_inwestor_pushButton_clicked)\r\n self.Numery_dzialek_textEdit.textChanged.disconnect(self.Numery_dzialek_textEdit_textChanged)\r\n self.Analizuj_pushButton.clicked.disconnect(self.Analizuj_pushButton_clicked)\r\n self.Przedmiot_textEdit.textChanged.disconnect(self.Przedmiot_textEdit_textChanged)\r\n self.Zapisz_przedmiot_pushButton.clicked.disconnect(self.Zapisz_przedmiot_pushButton_clicked)\r\n self.Csv_file_pushButton.clicked.disconnect(self.Csv_file_pushButton_clicked)\r\n self.Automat_pushButton.clicked.disconnect(self.Automat_pushButton_clicked)\r\n self.Generate_pushButton.clicked.disconnect(self.Generate_pushButton_clicked)\r\n self.Clear_pushButton.clicked.disconnect(self.Clear_pushButton_clicked)\r\n self.Prompt_pushButton.clicked.disconnect(self.Prompt_pushButton_clicked)\r\n self.Info_pushButton.clicked.disconnect(self.Info_pushButton_clicked)\r\n self.DOC_dB_connection_PostgreSQL.Stop_DB_connection()\r\n self.GGN_INFO_dB_connection_PostgreSQL.Stop_DB_connection()\r\n event.accept()\r\n\r\n\r\n #----------------------------------------------------------------------------------------------------------------\r\n # input widget methods:\r\n\r\n\r\n def Nr_dokumentu_lineEdit_textChanged(self):\r\n self.numer_dokumentu_w_sprawie = 0\r\n\r\n\r\n currently_edited_widget = None\r\n\r\n\r\n def Skladajacy_textEdit_textChanged(self):\r\n if not self.prompt_used_flag:\r\n self.currently_edited_widget = self.Skladajacy_textEdit\r\n tx = self.Skladajacy_textEdit.toPlainText().strip()\r\n if len(tx) > 0:\r\n self.Zapisz_skladajacy_pushButton.setEnabled(True)\r\n self.Prompt_pushButton.setEnabled(True)\r\n else:\r\n self.Zapisz_skladajacy_pushButton.setEnabled(False)\r\n self.Prompt_pushButton.setEnabled(False)\r\n else:\r\n self.Zapisz_skladajacy_pushButton.setEnabled(False)\r\n self.prompt_used_flag = False\r\n\r\n\r\n def Zapisz_skladajacy_pushButton_clicked(self):\r\n tx = self.Skladajacy_textEdit.toPlainText().strip()\r\n tx = self.clear_text(tx)\r\n if len(tx) > 0:\r\n if not self.is_present_in_adresaci_TAB(tx):\r\n INSERT_SQL = \"INSERT INTO adresaci (adres) VALUES('\" + tx + \"');\"\r\n print(\"Zapisz_skladajacy_pushButton_clicked, INSERT_SQL = \" + str(INSERT_SQL))\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(INSERT_SQL)\r\n if result == 'ERROR':\r\n self.DOC_dB_connection_PostgreSQL.Restart_DB_connection()\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(INSERT_SQL)\r\n print(\"Zapisz_skladajacy_pushButton_clicked, result = \" + str(result))\r\n else:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'TEKST JEST JUŻ W BAZIE DANYCH')\r\n self.Zapisz_skladajacy_pushButton.setEnabled(False)\r\n \r\n\r\n def Dzialajacy_checkBox_stateChanged(self):\r\n self.Inwestor_textEdit.setEnabled(self.Dzialajacy_checkBox.isChecked())\r\n self.Zapisz_inwestor_pushButton.setEnabled(self.Dzialajacy_checkBox.isChecked())\r\n\r\n\r\n def Inwestor_textEdit_textChanged(self):\r\n if not self.prompt_used_flag:\r\n self.currently_edited_widget = self.Inwestor_textEdit\r\n tx = self.Inwestor_textEdit.toPlainText().strip()\r\n if len(tx) > 0:\r\n self.Zapisz_inwestor_pushButton.setEnabled(True)\r\n self.Prompt_pushButton.setEnabled(True)\r\n else:\r\n self.Zapisz_inwestor_pushButton.setEnabled(False)\r\n self.Prompt_pushButton.setEnabled(False)\r\n else:\r\n self.Zapisz_inwestor_pushButton.setEnabled(False)\r\n self.prompt_used_flag = False\r\n\r\n\r\n def Zapisz_inwestor_pushButton_clicked(self):\r\n tx = self.Inwestor_textEdit.toPlainText().strip()\r\n tx = self.clear_text(tx)\r\n if len(tx) > 0:\r\n if not self.is_present_in_adresaci_TAB(tx):\r\n INSERT_SQL = \"INSERT INTO adresaci (adres) VALUES('\" + tx + \"');\"\r\n print(\"Zapisz_inwestor_pushButton_clicked, INSERT_SQL = \" + str(INSERT_SQL))\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(INSERT_SQL)\r\n if result == 'ERROR':\r\n self.DOC_dB_connection_PostgreSQL.Restart_DB_connection()\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(INSERT_SQL)\r\n print(\"Zapisz_inwestor_pushButton_clicked, result = \" + str(result))\r\n else:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'TEKST JEST JUŻ W BAZIE DANYCH')\r\n self.Zapisz_inwestor_pushButton.setEnabled(False)\r\n\r\n\r\n def Numery_dzialek_textEdit_textChanged(self):\r\n tx = self.Numery_dzialek_textEdit.toPlainText().strip()\r\n if len(tx) > 0:\r\n self.Analizuj_pushButton.setEnabled(True)\r\n else:\r\n self.Analizuj_pushButton.setEnabled(False)\r\n\r\n\r\n def Analizuj_pushButton_clicked(self):\r\n print('\\nAnalizuj_pushButton_clicked START ##################################################')\r\n self.text_filter.set_text(self.Numery_dzialek_textEdit.toPlainText().strip())\r\n parcel_list = self.text_filter.get_parcel_list()\r\n print('parcel_list = ' + str(parcel_list))\r\n if parcel_list:\r\n PARCEL_SELECT_SQL = \"SELECT id_umk, jednostka_nzw, rodzaj_wld_opis, opis_gr, uzytek_gr, numer_drogi, nazwa_ulicy FROM ggn_info WHERE id_umk = '\"\r\n sql = PARCEL_SELECT_SQL + \"' OR id_umk = '\".join(parcel_list) + \"';\"\r\n self.parcel_select_sql_result = self.GGN_INFO_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n if self.parcel_select_sql_result == 'ERROR':\r\n self.GGN_INFO_dB_connection_PostgreSQL.Restart_DB_connection()\r\n self.parcel_select_sql_result = self.GGN_INFO_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n if self.parcel_select_sql_result == 'ERROR':\r\n print(\"Analizuj_pushButton_clicked PROBLEM: self.parcel_select_sql_result == 'ERROR'\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, \"self.parcel_select_sql_result == 'ERROR'\")\r\n print('Analizuj_pushButton_clicked STOP ###################################################\\n')\r\n return\r\n if len(parcel_list) != len(self.parcel_select_sql_result):\r\n tmp_działki_list = parcel_list.copy()\r\n for res in self.parcel_select_sql_result:\r\n del(tmp_działki_list[tmp_działki_list.index(res[0])])\r\n print('Analizuj_pushButton_clicked PROBLEM: len(parcel_list) != len(self.parcel_select_sql_result), BRAK DANYCH DLA: ' + str(tmp_działki_list))\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'len(parcel_list) != len(self.parcel_select_sql_result), BRAK DANYCH DLA: ' + str(tmp_działki_list))\r\n print('\\n-----------------------------------------------------------------------------------')\r\n print('self.parcel_select_sql_result = ' + str(self.parcel_select_sql_result))\r\n print('\\n')\r\n if not self.parcel_select_sql_result:\r\n print('Analizuj_pushButton_clicked PROBLEM: BRAK DANYCH Z BAZY DANYCH DZIAŁEK EWIDENCYJNYCH')\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BRAK DANYCH Z BAZY DANYCH DZIAŁEK EWIDENCYJNYCH')\r\n print('Analizuj_pushButton_clicked STOP ###################################################\\n')\r\n return\r\n conv = lambda i : i or 'None'\r\n self.automat_map = self.get_initial_automat_map()\r\n skladajacy = self.Skladajacy_textEdit.toPlainText().strip()\r\n for res in self.parcel_select_sql_result:\r\n if res[2] == 'trwały zarząd': # rodzaj_wld_opis\r\n if res[5] is not None: # numer_drogi\r\n rodzaj = None\r\n for key, value in self.RODZAJ_MAP.items():\r\n if value.isChecked():\r\n rodzaj = key\r\n break\r\n if not rodzaj or rodzaj == 'lokalizację':\r\n print('Analizuj_pushButton_clicked PROBLEM: WYBIERZ RODZAJ (budowa, przebudowa lub remont)')\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'WYBIERZ RODZAJ (budowa, przebudowa lub remont)')\r\n print('Analizuj_pushButton_clicked STOP ###################################################\\n')\r\n return\r\n if rodzaj == 'budowę':\r\n self.automat_map['Decyzja - TEMPLATE.docx'].append(res[0])\r\n elif rodzaj == 'przebudowę' or rodzaj == 'remont':\r\n self.automat_map['Zgoda na przebudowę - TEMPLATE.docx'].append(res[0])\r\n else:\r\n print('Analizuj_pushButton_clicked PROBLEM: rodzaj(' + res[0] + ') = ' + str(rodzaj) + ' -> POMINIĘTO w automat_map')\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'rodzaj(' + res[0] + ') = ' + str(rodzaj) + ' -> POMINIĘTO w automat_map')\r\n else:\r\n self.automat_map['Zezwolenie - TEMPLATE.docx'].append(res[0])\r\n elif res[2] == 'administracja': # rodzaj_wld_opis\r\n if res[4] == 'dr': # uzytek_gr\r\n if not skladajacy or skladajacy.upper() == 'GGN':\r\n self.automat_map['Uzgodnienie + SŁUŻEBNOŚĆ - TEMPLATE.docx'].append(res[0])\r\n else:\r\n self.automat_map['Uzgodnienie + PRZEKAZANIE - TEMPLATE.docx'].append(res[0])\r\n else:\r\n if not skladajacy or skladajacy.upper() == 'GGN':\r\n self.automat_map['Opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx'].append(res[0])\r\n else:\r\n self.automat_map['Opinia + PRZEKAZANIE - TEMPLATE.docx'].append(res[0])\r\n else:\r\n print('Analizuj_pushButton_clicked, rodzaj_wld_opis(' + res[0] + ') = ' + str(res[2]) + ' -> POMINIĘTO w automat_map')\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'rodzaj_wld_opis(' + res[0] + ') = ' + str(res[2]) + ' -> POMINIĘTO w automat_map')\r\n if self.automat_map['Uzgodnienie + SŁUŻEBNOŚĆ - TEMPLATE.docx'] and self.automat_map['Opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx']:\r\n self.automat_map['Uzgodnienie i opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx'][0] += self.automat_map['Uzgodnienie + SŁUŻEBNOŚĆ - TEMPLATE.docx']\r\n self.automat_map['Uzgodnienie i opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx'][1] += self.automat_map['Opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx']\r\n self.automat_map['Uzgodnienie + SŁUŻEBNOŚĆ - TEMPLATE.docx'] = []\r\n self.automat_map['Opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx'] = []\r\n if self.automat_map['Uzgodnienie + PRZEKAZANIE - TEMPLATE.docx'] and self.automat_map['Opinia + PRZEKAZANIE - TEMPLATE.docx']:\r\n self.automat_map['Uzgodnienie i opinia + PRZEKAZANIE - TEMPLATE.docx'][0] += self.automat_map['Uzgodnienie + PRZEKAZANIE - TEMPLATE.docx']\r\n self.automat_map['Uzgodnienie i opinia + PRZEKAZANIE - TEMPLATE.docx'][1] += self.automat_map['Opinia + PRZEKAZANIE - TEMPLATE.docx']\r\n self.automat_map['Uzgodnienie + PRZEKAZANIE - TEMPLATE.docx'] = []\r\n self.automat_map['Opinia + PRZEKAZANIE - TEMPLATE.docx'] = []\r\n self.automat_map = self.remove_empty_elements_from_automat_map(self.automat_map)\r\n print('self.automat_map = ' + str(self.automat_map))\r\n if len(self.automat_map) == 0:\r\n self.Automat_pushButton.setEnabled(False)\r\n print('Analizuj_pushButton_clicked -> brak danych po analizie')\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'brak danych po analizie')\r\n print('Analizuj_pushButton_clicked STOP ###################################################\\n')\r\n return\r\n elif len(self.automat_map) == 1:\r\n self.Automat_pushButton.setEnabled(False)\r\n else:\r\n self.Automat_pushButton.setEnabled(True)\r\n print('\\n===================================================================================\\n')\r\n for key, value in self.automat_map.items():\r\n print(key)\r\n if key.startswith('Uzgodnienie i opinia'):\r\n print('UZGODNIENIE:')\r\n for p in value[0]:\r\n for res in self.parcel_select_sql_result:\r\n if res[0] == p:\r\n print(', '.join([conv(i) for i in res]))\r\n break\r\n print('OPINIA:')\r\n for p in value[1]:\r\n for res in self.parcel_select_sql_result:\r\n if res[0] == p:\r\n print(', '.join([conv(i) for i in res]))\r\n break\r\n else:\r\n for p in value:\r\n for res in self.parcel_select_sql_result:\r\n if res[0] == p:\r\n print(', '.join([conv(i) for i in res]))\r\n break\r\n print('\\n===================================================================================\\n')\r\n self.numer_dokumentu_w_sprawie = 0\r\n self.ustaw_dzialki_ulice_i_szablon(self.parcel_select_sql_result, self.automat_map, 0)\r\n else:\r\n print('Analizuj_pushButton_clicked PROBLEM: parcel_list = ' + str(parcel_list))\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BRAK DANYCH DZIAŁEK EWIDENCYJNYCH PO FILTROWANIU Z TEKSTU')\r\n print('Analizuj_pushButton_clicked STOP ###################################################\\n')\r\n\r\n\r\n def ustaw_dzialki_ulice_i_szablon(self, parcel_select_sql_result, automat_map, idx):\r\n if not parcel_select_sql_result:\r\n print('ustaw_dzialki_ulice_i_szablon PROBLEM: parcel_select_sql_result = ' + str(parcel_select_sql_result))\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'PROBLEM: parcel_select_sql_result = ' + str(parcel_select_sql_result))\r\n return False\r\n if not automat_map:\r\n print('ustaw_dzialki_ulice_i_szablon PROBLEM: automat_map = ' + str(automat_map))\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'PROBLEM: automat_map = ' + str(automat_map))\r\n return False\r\n if idx < 0 or len(automat_map) <= idx:\r\n print('automat_map = ' + str(automat_map))\r\n print('ustaw_dzialki_ulice_i_szablon PROBLEM: idx = ' + str(idx) + ' -> poza zakresem')\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'PROBLEM: idx = ' + str(idx) + ' -> poza zakresem')\r\n return False\r\n automat_map_keys = list(automat_map.keys())\r\n print('automat_map_keys[' + str(idx) + '] = ' + str(automat_map_keys[idx]))\r\n self.DOC_TEMPLATES_MAP[automat_map_keys[idx]].setChecked(True)\r\n nazwa_ulicy_list = []\r\n tmp_działki_list = []\r\n if automat_map_keys[idx].startswith('Uzgodnienie i opinia'):\r\n tx = 'UZGODNIENIE:\\n'\r\n tx += ', '.join(automat_map[automat_map_keys[idx]][0])\r\n tx += '\\nOPINIA:\\n'\r\n tx += ', '.join(automat_map[automat_map_keys[idx]][1])\r\n self.Numery_dzialek_textEdit.setText(tx)\r\n tmp_działki_list += automat_map[automat_map_keys[idx]][0]\r\n tmp_działki_list += automat_map[automat_map_keys[idx]][1]\r\n else:\r\n self.Numery_dzialek_textEdit.setText(', '.join(automat_map[automat_map_keys[idx]]))\r\n tmp_działki_list += automat_map[automat_map_keys[idx]]\r\n print('tmp_działki_list = ' + str(tmp_działki_list))\r\n for p in tmp_działki_list:\r\n for res in parcel_select_sql_result:\r\n if res[0] == p:\r\n nazwa_ulicy = res[-1]\r\n if nazwa_ulicy:\r\n nazwa_ulicy_list.append(nazwa_ulicy.strip())\r\n break\r\n nazwa_ulicy_list = list(set(nazwa_ulicy_list))\r\n print('nazwa_ulicy_list = ' + str(nazwa_ulicy_list))\r\n if nazwa_ulicy_list:\r\n self.Ulice_textEdit.setText(', '.join(nazwa_ulicy_list))\r\n else:\r\n self.Ulice_textEdit.setText('.......................')\r\n return True\r\n \r\n\r\n def Przedmiot_textEdit_textChanged(self):\r\n if not self.prompt_used_flag:\r\n self.currently_edited_widget = self.Przedmiot_textEdit\r\n tx = self.Przedmiot_textEdit.toPlainText().strip()\r\n if len(tx) > 0:\r\n self.Zapisz_przedmiot_pushButton.setEnabled(True)\r\n self.Prompt_pushButton.setEnabled(True)\r\n else:\r\n self.Zapisz_przedmiot_pushButton.setEnabled(False)\r\n self.Prompt_pushButton.setEnabled(False)\r\n else:\r\n self.Zapisz_przedmiot_pushButton.setEnabled(False)\r\n self.prompt_used_flag = False\r\n\r\n\r\n def Zapisz_przedmiot_pushButton_clicked(self):\r\n tx = self.Przedmiot_textEdit.toPlainText().strip()\r\n tx = tx.replace('\\n', ' ')\r\n tx = tx.replace(' ,', ', ')\r\n tx = self.replace_loop(tx, ' ', ' ')\r\n tx = tx.strip()\r\n if len(tx) > 0:\r\n if not self.is_present_in_przedmioty_TAB(tx):\r\n INSERT_SQL = \"INSERT INTO przedmioty (przedmiot) VALUES('\" + tx + \"');\"\r\n print(\"Zapisz_przedmiot_pushButton_clicked, INSERT_SQL = \" + str(INSERT_SQL))\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(INSERT_SQL)\r\n if result == 'ERROR':\r\n self.DOC_dB_connection_PostgreSQL.Restart_DB_connection()\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(INSERT_SQL)\r\n print(\"Zapisz_przedmiot_pushButton_clicked, result = \" + str(result))\r\n else:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'TEKST JEST JUŻ W BAZIE DANYCH')\r\n self.Zapisz_przedmiot_pushButton.setEnabled(False)\r\n\r\n\r\n def Csv_file_pushButton_clicked(self):\r\n if self.parcel_select_sql_result:\r\n nr_sprawy = self.Nr_dokumentu_lineEdit.text().strip()\r\n nr_sprawy_list = nr_sprawy.split('.')\r\n if len(nr_sprawy_list) != 4:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNY NUMER SPRAWY')\r\n return\r\n file_path = os.path.join(self.DECYZJE_FOLDER_PATH, nr_sprawy_list[2] + ' - działki tab.csv')\r\n f = codecs.open(file_path, 'w', 'utf-8')\r\n for res in self.parcel_select_sql_result:\r\n conv = lambda i : i or 'None'\r\n f.write(';'.join([conv(i) for i in res]) + '\\n')\r\n f.close()\r\n print('Csv_file_pushButton_clicked, dane zapisano do pliku: ' + file_path)\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'dane zapisano do pliku: ' + file_path)\r\n else:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BRAK DANYCH')\r\n\r\n\r\n def Automat_pushButton_clicked(self):\r\n print('Automat_pushButton_clicked')\r\n self.numer_dokumentu_w_sprawie = 0\r\n for idx in range(len(self.automat_map)):\r\n if not self.ustaw_dzialki_ulice_i_szablon(self.parcel_select_sql_result, self.automat_map, idx):\r\n break\r\n if not self.Generate_pushButton_clicked():\r\n break\r\n\r\n\r\n def Generate_pushButton_clicked(self):\r\n template_file_name = None\r\n for key, value in self.DOC_TEMPLATES_MAP.items():\r\n if value.isChecked():\r\n template_file_name = key\r\n break\r\n print(\"Generate_pushButton_clicked, template_file_name = \" + str(template_file_name))\r\n if not template_file_name:\r\n print(\"Generate_pushButton_clicked, PROBLEM: WYBIERZ SZABLON DOKUMENTU\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'WYBIERZ SZABLON DOKUMENTU')\r\n return False\r\n doc = Document(os.path.join('templates', template_file_name))\r\n rodzaj = None\r\n for key, value in self.RODZAJ_MAP.items():\r\n if value.isChecked():\r\n rodzaj = key\r\n break\r\n if not rodzaj:\r\n print(\"Generate_pushButton_clicked, PROBLEM: WYBIERZ RODZAJ\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'WYBIERZ RODZAJ')\r\n return False\r\n self.replace_text_DOCX(doc, '[RODZAJ]', rodzaj)\r\n self.replace_text_DOCX(doc, '+[DATA_DZISIEJSZA]', self.get_time_str())\r\n if template_file_name not in self.DOC_TEMPLATES_NO_SENDER_LIST:\r\n adres_skladajacego = self.Skladajacy_textEdit.toPlainText().strip()\r\n if not adres_skladajacego:\r\n print(\"Generate_pushButton_clicked, PROBLEM: BŁĘDNY ADRES SKŁADAJĄCEGO\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNY ADRES SKŁADAJĄCEGO')\r\n return False\r\n if self.Dzialajacy_checkBox.isChecked():\r\n adres_inwestora = self.Inwestor_textEdit.toPlainText().strip()\r\n if not adres_inwestora:\r\n print(\"Generate_pushButton_clicked, PROBLEM: BŁĘDNY ADRES INWESTORA\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNY ADRES INWESTORA')\r\n return False\r\n adres_strony = adres_skladajacego + '\\ndziałający w imieniu i na rzecz\\n' + adres_inwestora\r\n else:\r\n adres_strony = adres_skladajacego\r\n self.replace_text_DOCX(doc, '[ADRES_STRONY]', adres_strony)\r\n self.replace_text_DOCX(doc, '[ADRES_STRONY_W_LINII]', self.clear_text(adres_skladajacego))\r\n numery_dzialek = self.Numery_dzialek_textEdit.toPlainText().strip()\r\n if not numery_dzialek:\r\n print(\"Generate_pushButton_clicked, PROBLEM: BŁĘDNY NUMER DZIAŁKI\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNY NUMER DZIAŁKI')\r\n return False\r\n if template_file_name.startswith('Uzgodnienie i opinia'):\r\n if numery_dzialek.startswith('UZGODNIENIE:') and 'OPINIA:' in numery_dzialek:\r\n numery_dzialek = numery_dzialek.replace('UZGODNIENIE:', '')\r\n numery_dzialek_list = numery_dzialek.split('OPINIA:')\r\n if len(numery_dzialek_list) == 2:\r\n numery_dzialek = self.clear_text(numery_dzialek_list[0])\r\n numery_dzialek_2 = self.clear_text(numery_dzialek_list[1])\r\n self.replace_text_DOCX(doc, '[NUMERY_DZIAŁEK_2]', numery_dzialek_2)\r\n self.replace_text_DOCX(doc, '[NUMERY_DZIAŁEK]', numery_dzialek)\r\n nazwa_ulicy = self.Ulice_textEdit.toPlainText().strip()\r\n if not nazwa_ulicy:\r\n print(\"Generate_pushButton_clicked, PROBLEM: BŁĘDNY NAZWA ULICY\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNA NAZWA ULICY')\r\n return False\r\n self.replace_text_DOCX(doc, '[NAZWA_ULICY]', nazwa_ulicy)\r\n przedmiot = self.Przedmiot_textEdit.toPlainText().strip()\r\n if not przedmiot:\r\n print(\"Generate_pushButton_clicked, PROBLEM: BŁĘDNY NAZWA PRZEDMIOTU\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNA NAZWA PRZEDMIOTU')\r\n return False\r\n self.replace_text_DOCX(doc, '[PRZEDMIOT]', przedmiot)\t\r\n nr_sprawy = self.Nr_dokumentu_lineEdit.text().strip()\r\n nr_sprawy_list = nr_sprawy.split('.')\r\n if len(nr_sprawy_list) != 4:\r\n print(\"Generate_pushButton_clicked, PROBLEM: BŁĘDNY NUMER SPRAWY\")\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNY NUMER SPRAWY')\r\n return False\r\n if self.numer_dokumentu_w_sprawie > 0:\r\n nr_sprawy = nr_sprawy_list[0] + '.' + nr_sprawy_list[1] + '.' + nr_sprawy_list[2] + '-' + str(self.numer_dokumentu_w_sprawie) + '.' + nr_sprawy_list[3]\r\n self.replace_text_DOCX(doc, '[NUMER_SPRAWY]', nr_sprawy)\r\n self.numer_dokumentu_w_sprawie += 1\r\n self.save_document(nr_sprawy, nazwa_ulicy, self.DECYZJE_FOLDER_PATH, template_file_name, doc)\r\n return True\r\n \r\n\r\n def Clear_pushButton_clicked(self):\r\n self.Nr_dokumentu_lineEdit.setText(\"TE.4061.\")\r\n self.Skladajacy_textEdit.setText(\"\")\r\n self.Inwestor_textEdit.setText(\"\")\r\n self.Numery_dzialek_textEdit.setText(\"\")\r\n self.Ulice_textEdit.setText(\"\")\r\n self.Przedmiot_textEdit.setText(\"\")\r\n self.Inwestor_textEdit.setEnabled(False)\r\n self.Zapisz_skladajacy_pushButton.setEnabled(False)\r\n self.Zapisz_inwestor_pushButton.setEnabled(False)\r\n self.Analizuj_pushButton.setEnabled(False)\r\n self.Zapisz_przedmiot_pushButton.setEnabled(False)\r\n self.Prompt_pushButton.setEnabled(False)\r\n self.Automat_pushButton.setEnabled(False)\r\n self.Dzialajacy_checkBox.setChecked(False)\r\n self.Lokalizacja_radioButton.setChecked(True)\r\n self.remove_widgets_from_gridLayout()\r\n self.prompt_used_flag = False\r\n self.parcel_select_sql_result = None\r\n self.automat_map = None\r\n self.numer_dokumentu_w_sprawie = 0\r\n \r\n\r\n def Prompt_pushButton_clicked(self):\r\n if self.currently_edited_widget:\r\n self.remove_widgets_from_gridLayout()\r\n if self.currently_edited_widget == self.Przedmiot_textEdit:\r\n SQL = \"SELECT przedmiot FROM przedmioty WHERE przedmiot ~* '\" + self.currently_edited_widget.toPlainText().strip() + \"';\"\r\n else: # self.Skladajacy_textEdit lub self.Inwestor_textEdit\r\n SQL = \"SELECT adres FROM adresaci WHERE adres ~* '\" + self.currently_edited_widget.toPlainText().strip() + \"';\"\r\n self.fill_gridLayout(SQL)\r\n else:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BRAK DANYCH')\r\n\r\n\r\n def Info_pushButton_clicked(self):\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, SCRIPT_TITLE + ' v. ' + SCRIPT_VERSION + '\\n\\n' + GENERAL_INFO)\r\n\r\n\r\n #----------------------------------------------------------------------------------------------------------------\r\n # gridLayout methods:\r\n\r\n\r\n My_QLabel_WIDTH = 200\r\n My_QLabel_HEIGHT = 50\r\n\r\n\r\n def fill_gridLayout(self, sql):\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n if result == 'ERROR':\r\n self.DOC_dB_connection_PostgreSQL.Restart_DB_connection()\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n print(\"fill_gridLayout, result = \" + str(result))\r\n row = 0\r\n for record in result:\r\n self.gridLayout.addWidget(self.get_QLabel(self.restore_text(str(record[0]))), row, 0, QtCore.Qt.AlignTop)\r\n self.gridLayout.setRowStretch(row, 1)\r\n row += 1\r\n if row >= 10:\r\n break\r\n self.gridLayout.addWidget(QtWidgets.QLabel(), row, 0, QtCore.Qt.AlignTop) # dopełnienie od dołu, żeby \"przepchnąć\" etykiety do góry\r\n self.gridLayout.setRowStretch(row, 5)\r\n\r\n\r\n prompt_used_flag = False\r\n \r\n\r\n def set_selected_text_QLabel(self, text):\r\n if self.currently_edited_widget:\r\n self.prompt_used_flag = True\r\n self.currently_edited_widget.setText(text)\r\n else:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BRAK DANYCH')\r\n\r\n\r\n def get_QLabel(self, text):\r\n _tmp_label = My_QLabel(self, text)\r\n _tmp_label.setMinimumSize(self.My_QLabel_WIDTH, self.My_QLabel_HEIGHT)\r\n _tmp_label.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Expanding))\r\n _tmp_label.setStyleSheet(\"border: 1px solid black;\")\r\n _tmp_label.setText(text)\r\n return _tmp_label\r\n\r\n\r\n def remove_widgets_from_gridLayout(self):\r\n for i in reversed(range(self.gridLayout.count())):\r\n _widget_to_remove = self.gridLayout.itemAt(i).widget()\r\n self.gridLayout.removeWidget(_widget_to_remove)\r\n _widget_to_remove.setParent(None)\r\n del _widget_to_remove\r\n\r\n\r\n #----------------------------------------------------------------------------------------------------------------\r\n # auxiliary methods:\r\n \r\n\r\n def clear_text(self, text):\r\n if text.startswith('\\n'):\r\n text = text[1:]\r\n if text.startswith(','):\r\n text = text[1:]\r\n text = text.replace('\\n', ', ')\r\n text = text.replace(' ,', ', ')\r\n text = self.replace_loop(text, ' ', ' ')\r\n return text.strip()\r\n\r\n\r\n def restore_text(self, text):\r\n tx = text.replace(', ', '\\n')\r\n return tx\r\n\r\n\r\n def replace_loop(self, text, old_tx, new_tx):\r\n while True:\r\n n = len(text)\r\n text = text.replace(old_tx, new_tx)\r\n if n == len(text):\r\n break\r\n return text\r\n\r\n\r\n def replace_text_DOCX(self, doc, old_tx, new_tx):\r\n found = False\r\n for p in doc.paragraphs:\r\n if old_tx in p.text:\r\n inline = p.runs\r\n for i in range(len(inline)):\r\n if old_tx in inline[i].text:\r\n inline[i].text = inline[i].text.replace(old_tx, str(new_tx))\r\n found = True\r\n if found:\r\n print('replace_text_DOCX: ' + str(old_tx) + ' -> ' + str(new_tx))\r\n else:\r\n print('replace_text_DOCX: ' + old_tx + ' NOT FOUND')\r\n\r\n\r\n def get_time_str(self):\r\n return str(datetime.datetime.now().strftime('%d.%m.%Y'))\r\n\r\n\r\n def save_document(self, nr_sprawy, nazwa_ulicy, result_dir_path, template_file_name, doc):\r\n nr_sprawy_list = nr_sprawy.split('.')\r\n if len(nr_sprawy_list) != 4:\r\n QtWidgets.QMessageBox.information(self, SCRIPT_TITLE, 'BŁĘDNY NUMER SPRAWY')\r\n return\r\n if len(nazwa_ulicy) > 20:\r\n nazwa_ulicy = nazwa_ulicy[0:20]\r\n nazwa_pliku_wynikowego = nr_sprawy_list[2] + ' - ' + template_file_name.replace('TEMPLATE', nazwa_ulicy)\r\n result_file_path = os.path.join(result_dir_path, nazwa_pliku_wynikowego)\r\n doc.save(result_file_path)\r\n print('save_document, zapisano do: ' + result_file_path)\r\n\r\n\r\n def is_present_in_adresaci_TAB(self, tx):\r\n sql = \"SELECT adres FROM adresaci WHERE adres = '\" + tx + \"';\"\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n if result == 'ERROR':\r\n self.DOC_dB_connection_PostgreSQL.Restart_DB_connection()\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n return result\r\n\r\n\r\n def is_present_in_przedmioty_TAB(self, tx):\r\n sql = \"SELECT przedmiot FROM przedmioty WHERE przedmiot = '\" + tx + \"';\"\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n if result == 'ERROR':\r\n self.DOC_dB_connection_PostgreSQL.Restart_DB_connection()\r\n result = self.DOC_dB_connection_PostgreSQL.Send_SQL_to_DB(sql)\r\n return result\r\n\r\n\r\n def get_initial_automat_map(self):\r\n return {\r\n 'Decyzja - TEMPLATE.docx': [],\r\n 'Zgoda na przebudowę - TEMPLATE.docx': [],\r\n 'Zezwolenie - TEMPLATE.docx': [],\r\n 'Uzgodnienie + SŁUŻEBNOŚĆ - TEMPLATE.docx': [],\r\n 'Uzgodnienie + PRZEKAZANIE - TEMPLATE.docx': [],\r\n 'Uzgodnienie i opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx': [[], []],\r\n 'Uzgodnienie i opinia + PRZEKAZANIE - TEMPLATE.docx': [[], []],\r\n 'Opinia + SŁUŻEBNOŚĆ - TEMPLATE.docx': [],\r\n 'Opinia + PRZEKAZANIE - TEMPLATE.docx': []\r\n }\r\n\r\n\r\n def remove_empty_elements_from_automat_map(self, automat_map):\r\n if automat_map:\r\n for k in automat_map.copy().keys():\r\n if len(automat_map[k]) <= 1:\r\n if not automat_map[k]:\r\n del(automat_map[k])\r\n else:\r\n if not automat_map[k][0] and not automat_map[k][1]:\r\n del(automat_map[k])\r\n if automat_map:\r\n return automat_map\r\n return None\r\n\r\n\r\n#====================================================================================================================\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = QtWidgets.QApplication(sys.argv)\r\n madeline = Madeline()\r\n madeline.show()\r\n sys.exit(app.exec_())\r\n\r\n\r\n\r\n","repo_name":"piotrm35/Madeline","sub_path":"Madeline_1.2.py","file_name":"Madeline_1.2.py","file_ext":"py","file_size_in_byte":40413,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"29777769547","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\nwith open('README.md') as f:\n readme = f.read()\n\nwith open('LICENSE') as f:\n license = f.read()\n\nsetup(\n name='histone_code_vae',\n version='0.1.0',\n description='Sample package for Python-Guide.org',\n long_description=readme,\n author='Rick Farouni',\n author_email='rfarouni@gmail.com',\n url='https://github.com/rfarouni/histone_code_vae',\n license=license,\n packages=find_packages(exclude=('tests', 'docs', 'r_code'))\n)\n\n","repo_name":"rfarouni/histone_code_vae","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"14047211670","text":"def g(max):\n count, a, b = 0, 0, 1\n while True:\n if count > max :\n break\n yield a \n a, b = b, a + b\n count += 1\n \nfor i in g(100):\n print(i, end= ',')","repo_name":"callor/Callor-Python-2017","sub_path":"Algorithm/Fibonache2.py","file_name":"Fibonache2.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"30592449499","text":"import numpy as np\nimport cv2\nfrom utils import round_nearest\n\nclass BoardImageTranslator():\n def __init__(self):\n self.origin = np.array([0, 0])\n\n def fit(self, img_points, board_points, img):\n result = self.calculate_homography(img_points, board_points, img)\n if not result:\n return False\n\n H, H_inv = result\n self.H = H\n self.H_inv = H_inv\n self.img_points = img_points\n self.board_points = board_points\n\n return True\n\n def refine(self, new_img_points, new_board_points, img):\n new_img_points = np.array(new_img_points)\n new_board_points = np.array(new_board_points) * 64\n\n self.img_points = np.append(self.img_points, new_img_points, axis=0)\n self.board_points = np.append(self.board_points, new_board_points, axis=0)\n\n H, H_inv = self.calculate_homography(self.img_points, self.board_points, img)\n self.H = H\n self.H_inv = H_inv\n\n def is_reasonable_homography(self, H_inv):\n def board_p_to_image_p(p):\n p = np.array(p)\n p = np.append(p, 1)\n image_point = H_inv.dot(p.reshape(3, 1))\n image_point = np.squeeze(image_point)\n image_point = image_point[:2] / image_point[2]\n image_point = image_point.astype('int64')\n return image_point\n\n for x_i, y_i in np.ndindex((5, 5)):\n x = x_i * 64\n y = y_i * 64\n p1 = board_p_to_image_p((x, y))\n p2 = board_p_to_image_p((x, y + 64))\n p3 = board_p_to_image_p((x + 64, y))\n dist_p1_p2 = np.linalg.norm(p1 - p2)\n dist_p1_p3 = np.linalg.norm(p1 - p3)\n if max(dist_p1_p2, dist_p1_p3) > 80 and np.abs(dist_p1_p3 - dist_p1_p2) >= 0.5 * min(dist_p1_p2, dist_p1_p3):\n print('distances:', dist_p1_p2, dist_p1_p3)\n return False\n\n return True\n\n def calculate_homography(self, img_points, board_points, img):\n # make copy b/c of weird layout bug\n # open cv complains if we use image_points directly\n copy = []\n for p in img_points:\n copy.append(p)\n copy = np.array(copy, dtype=np.float32)\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 30, 0.001)\n cv2.cornerSubPix(gray_img, copy, (5, 5), (-1, -1), criteria)\n img_points = copy\n\n H_inv, _ = cv2.findHomography(board_points, img_points, cv2.RANSAC, 5.0)\n if H_inv is None:\n print('Could not generate homography. Aborting.')\n return None\n\n if not self.is_reasonable_homography(H_inv):\n print('Generated homography does not look correct. Aborting.')\n return None\n\n H, _ = cv2.findHomography(img_points, board_points, cv2.RANSAC, 5.0)\n\n return H, H_inv\n\n def new_translator_with_img_origin(self, origin):\n new = BoardImageTranslator()\n new.img_points = self.img_points\n new.board_points = self.board_points\n new.H = self.H\n new.H_inv = self.H_inv\n\n board_origin = self.img_p_to_board_p(origin)\n new.origin = np.array(board_origin)\n\n return new\n\n def get_img_origin(self):\n return self.board_p_to_img_p((0, 0))\n\n def board_p_to_img_p(self, p):\n p = np.array(p)\n p += self.origin\n p *= 64\n p = np.append(p, 1)\n image_point = self.H_inv.dot(p.reshape(3, 1))\n image_point = np.squeeze(image_point)\n image_point = image_point[:2] / image_point[2]\n image_point = image_point.astype(np.int32)\n\n return image_point\n\n def img_p_to_board_p(self, p):\n p = np.array(p)\n p = np.append(p, 1)\n board_p = self.H.dot(p.reshape(3, 1))\n board_p = np.squeeze(board_p)\n board_p = board_p[:2] / board_p[2]\n board_p = board_p.astype(np.int32)\n board_p -= self.origin\n\n nearest_x = int(round_nearest(board_p[0], 64) / 64)\n nearest_y = int(round_nearest(board_p[1], 64) / 64)\n\n return (nearest_x, nearest_y)\n\n def board_pos_from_box(self, box):\n min_x = 1000\n min_y = 1000\n for img_p in box:\n board_p = self.img_p_to_board_p(img_p)\n min_x = min(board_p[0], min_x)\n min_y = min(board_p[1], min_y)\n\n return (min_x, min_y)\n\n def tile_img_from_box(self, img, box):\n point_map = {}\n for img_p in box:\n board_p = self.img_p_to_board_p(img_p)\n point_map[board_p] = img_p\n img_pts = [point_map[key] for key in sorted(point_map.keys())]\n tl = img_pts[0]\n bl = img_pts[1]\n tr = img_pts[2]\n br = img_pts[3]\n\n world_points = np.array([[0, 0],\n [64, 0],\n [64, 64],\n [0, 64]], dtype=np.float32)\n img_points = np.array([tl, tr, br, bl], dtype=np.float32)\n transform = cv2.getPerspectiveTransform(img_points, world_points)\n tile = cv2.warpPerspective(img, transform, (64, 64))\n\n return tile\n\n def board_pos_to_tile_bbox(self, pos):\n x, y = pos\n tl = self.board_p_to_img_p((x, y))\n tr = self.board_p_to_img_p((x + 1, y))\n bl = self.board_p_to_img_p((x, y + 1))\n br = self.board_p_to_img_p((x + 1, y + 1))\n\n img_x, img_y, w, h = cv2.boundingRect(np.array([tl, br, bl, br]))\n\n return ((img_x, img_y), (img_x+w, img_y+h))\n\n def tile_img_at_pos(self, img, pos):\n x_index, y_index = pos\n tl = self.board_p_to_img_p((x_index, y_index))\n tr = self.board_p_to_img_p((x_index + 1, y_index))\n br = self.board_p_to_img_p((x_index + 1, y_index + 1))\n bl = self.board_p_to_img_p((x_index, y_index + 1))\n\n world_points = np.array([[0, 0],\n [64, 0],\n [64, 64],\n [0, 64]], dtype=np.float32)\n img_points = np.array([tl, tr, br, bl], dtype=np.float32)\n transform = cv2.getPerspectiveTransform(img_points, world_points)\n tile = cv2.warpPerspective(img, transform, (64, 64))\n\n return tile","repo_name":"adrientruong/carcassonne","sub_path":"code/board_img_translator.py","file_name":"board_img_translator.py","file_ext":"py","file_size_in_byte":6267,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"80"} +{"seq_id":"4103599863","text":"\"\"\"\nDjango settings for proj project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\n# Also, make sure to store in an environment variable\nSECRET_KEY = 'scbxb6+g$o3=)0ja+a3))v&#@n8afd-xg)d_@3#^u8-8xl+%0x'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'main',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'proj.urls'\n\nWSGI_APPLICATION = 'proj.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'db_name', # Or path to database file if using sqlite3.\n 'USER': 'admin',\n 'PASSWORD': 'password',\n 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n 'PORT': '', # Set to empty string for default.\n 'TEST_NAME': 'db_name_test',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n\nAUTH_USER_MODEL = 'main.User'\n","repo_name":"azul-cloud/start","sub_path":"settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"71608151297","text":"#!/usr/bin/env python\n\n__author__ = 'Leslie Tom'\n__email__ = 'leslie.tom@gmail.com'\n__python_version__ = '3.2.3'\n\n#Import datetime to create datetime objects.\nfrom datetime import datetime\n\nclass Project:\n def __init__(self, line):\n '''\n Instantiates all the variables from the lines read in from the csv file.\n '''\n cells= line.split(',')\n #calling organization_category \"Project\"\n self.organization_category = cells[0] \n self.project_title = cells[1]\n self.project_description = cells[2]\n self.start_date = self.parse_date(cells[3]) ##need to change into a date object -- and is there a way to parse through and have project print for each year?\n self.end_date = self.parse_date(cells[4]) ##need to change into a date object\n self.tools = self.clean_string_colon(cells, 5)\n self.num_of_people_experienced = cells[6]\n self.places = cells[7]\n #organized based on phases -- filtering by final phase of projects 'construction'\n self.phase_name = cells[8].strip()\n self.fullproject_title = cells[9]\n self.image_urls = cells[10]\n self.organization_names = cells[11]\n self.about = cells[12]\n self.project_id = cells[13]\n \n #Leslie experimented with this def. This takes out the \":\" -- but does not split apart the cells. (split() does not work) \n def clean_string_colon(self, cells, index):\n try:\n return cells[index].strip().replace(':', '')\n except:\n return ''\n \n #Sarah helped me make a start_year to plug into get_project method\n def start_year(self):\n return self.start_date.strftime('%Y')\n \n def end_year(self):\n return self.end_date.strftime('Y')\n \n #Sarah helped me make parse date and Output year methods.\n def parse_date(self, date_string):\n '''\n Changes start_date and end_date to date objects\n '''\n mydate = datetime.strptime(date_string, '%m/%d/%Y') #11/13/2011\n return mydate\n \n def output_year(self, mydate):\n return mydate.strftime('%Y')\n \n\nclass DataController:\n def __init__(self):\n self.projects = []\n \n #Sarah helped me find the file directory path and worked on cleaning up my csv data from using Excel and spliting on ';'\n def read_file(self, file_name='/Users/leslietom/Dropbox/iSchool Berkeley/i206summer/i206_Final Project/website/static/data/2012portfolio_leslie1.csv'):\n '''\n Reads a file and populates self.projects with a list of Project objects\n '''\n f = open(file_name)\n for line in f.readlines()[1:]:\n print(line)\n self.projects.append(Project(line))\n f.close()\n\n #Worked with Sarah 6/27/12 to help get all projects.\n def get_all_projects(self):\n '''\n Returns a list of all projects.\n '''\n return self.projects\n \n #Leslie tried to just get the 'construction' phase to show for the main page. Still in progress - to be tied into index.\n def get_project_phases(self, project_id):\n '''\n Returns a list of projects where the phase name matches. This also tells which resource initially shows.\n '''\n #create an empty projects list.\n projects = []\n for project in self.projects:\n #When user clicks on image of \"construction\" projects - this will iterate through objects and append a project list for matching project_id's.\n if project.project_id == project_id:\n projects.append(project)\n return projects\n\n #Sarah helped to start - a method that passes everything. 6/27/12\n #\n def get_projects(self, org=None, phase=None, year=None, num_people=None, place=None, tool=None, image_url=None):\n '''\n Returns a list of all projects. This also tells which resource initially shows.\n '''\n projects = []\n for project in self.projects:\n if ((org is None or project.organization_category == org) and\n (year is None or project.start_year() == year) and\n (num_people is None or project.num_of_people_experienced == num_people) and\n (place is None or project.places == place) and\n (tool is None or project.tools == tool) and\n (image_url is None or project.image_urls == image_url)):\n projects.append(project)\n return projects\n \n #Leslie tried to just get the 'construction' phase to show for the main page.\n def get_construction_projects(self, org=None, phase='Construction', year=None, num_people=None, place=None, tool=None, image_url=None):\n '''\n Returns a list of projects where the phase name matches. \n '''\n projects = []\n for project in self.projects:\n #To be used for splash page. \n if (project.phase_name == phase and\n (org is None or project.organization_category == org) and\n (year is None or project.start_year() == year) and\n (num_people is None or project.num_of_people_experienced == num_people) and\n (place is None or project.places == place) and\n (tool is None or project.tools == tool) and\n (image_url is None or project.image_urls == image_urls)):\n projects.append(project)\n return projects\n \n #Leslie trying to experiment with getting year.\n def get_a_year(self, year=None):\n projects = []\n for project in self.projects:\n if year is None or project.start_year == year:\n projects.append(project)\n return projects\n \n #Using this method to return all project id's to group projects.\n def get_allproject_ids(self, project_id=None):\n '''\n Returns a list of project ids. \n '''\n projects = []\n for project in self.projects:\n if project.project_id == project_id:\n projects.append(project)\n return projects\n \n #This method may return blank output on base.HTML page because did not tie end dates into HTML.\n def get_years(self):\n '''\n Returns a unique list of all start and end dates.\n '''\n #create a set to get all unique values.\n years = set()\n for project in self.projects:\n years.add(project.output_year(project.start_date))\n years.add(project.output_year(project.end_date))\n #turn set into a list\n years = list(years)\n #have the most recent years printed out first.\n years.sort(reverse=True) \n return years\n \n def get_orgs(self):\n '''\n Returns a list of projects where the get organizations matches. This is called projects in HTML.\n '''\n organizations = set()\n for project in self.projects:\n organizations.add(project.organization_category) #for set\n organizations = list(organizations)\n organizations.sort()\n return organizations\n \n def get_num_ppl(self):\n '''\n Returns a list of projects where the number of people experienced matches.\n '''\n people = set()\n for project in self.projects:\n people.add(project.num_of_people_experienced) \n people = list(people)\n people.sort()\n return people\n \n def get_places(self):\n '''\n Returns a list of project locations / places.\n '''\n places = set()\n for project in self.projects:\n places.add(project.places) \n places = list(places)\n places.sort()\n return places\n \n def get_tools(self):\n '''\n Returns a list of tools used.\n '''\n tools = set()\n for project in self.projects:\n tools.add(project.tools) #for set\n tools = list(tools)\n tools.sort()\n return tools\n \n def get_image_urls(self):\n '''\n Returns a list of urls images from Flickr\n '''\n image_urls = set()\n for project in self.projects:\n image_urls.add(project.image_urls)\n image_urls = list(image_urls)\n image_urls.sort()\n return image_urls\n","repo_name":"leslietom/Portfolio","sub_path":"model/portfolio_model.py","file_name":"portfolio_model.py","file_ext":"py","file_size_in_byte":8328,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"39962187559","text":"class Solution:\n\tdef longestValidParentheses(self, s: str) -> int:\n\t\tdp = [0] * len(s)\n\t\tres = 0\n\t\tfor i in range(1, len(s)):\n\t\t\tif s[i] == ')':\n\t\t\t\tif s[i-1] == '(':\n\t\t\t\t\tif i >= 2:\n\t\t\t\t\t\tdp[i] = dp[i-2] + 2\n\t\t\t\t\telse:\n\t\t\t\t\t\tdp[i] = 2\n\t\t\t\telse:\n\t\t\t\t\tif i - dp[i-1] - 1 >= 0 and s[i - dp[i-1] - 1] == '(':\n\t\t\t\t\t\tif i - dp[i-1] - 2 >= 0 and s[i - dp[i-1] - 2] == ')':\n\t\t\t\t\t\t\tdp[i] = dp[i-1] + dp[i - dp[i-1] - 2] + 2\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdp[i] = dp[i-1] + 2\n\t\t\tres = max(res, dp[i])\n\t\t\t\n\t\treturn res\n\t\n\nif __name__ == '__main__':\n\tx = Solution()\n\tT = int(input())\n\twhile T > 0:\n\t\tT -= 1\n\t\ts = input()\n\t\tprint(x.longestValidParentheses(s))","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2474/60665/282280.py","file_name":"282280.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"40043702629","text":"def func(list1):\n sum1=sum(list1)\n s=int(sum1/3)\n t1=0\n t2=0\n it=0\n while(t1 3:\n job_id = scheduler.get_jobs()[0]\n print(job_id)\n scheduler.remove_job('timer')\n print(diff)\n\n\n\n\nif __name__ == '__main__':\n scheduler = BackgroundScheduler()\n scheduler_starttime = time.time()\n scheduler.add_job(lambda: tick(scheduler_starttime), 'interval', seconds=1, id='timer')\n scheduler.start()\n print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))\n\n try:\n # This is here to simulate application activity (which keeps the main thread alive).\n while True:\n time.sleep(2)\n except (KeyboardInterrupt, SystemExit):\n # Not strictly necessary if daemonic mode is enabled but should be done if possible\n scheduler.shutdown()","repo_name":"RyosukeTakahashi/InsiderLinebot","sub_path":"tempscript.py","file_name":"tempscript.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"29210316734","text":"from django.shortcuts import render\nimport json as JSON\nimport os\n\nBASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'result'))\n\ndef resultIndex(request):\n\treturn render( request, \"resultindex.html\")\n\ndef extractDataFromFile(fileName):\n\twith open(os.path.join(BASE_PATH, fileName), 'r') as file:\n\t\tcontent = file.read().split('\\n')\n\n\tdata = []\n\tfor ind in range(1, len(content)):\n\t\tif len(content[ind].split('\\t')) > 7:\n\t\t\trecord = dict(\n\t\t\t\tTEST_ID = content[ind].split('\\t')[0],\n\t\t\t\tTEST_CASE = content[ind].split('\\t')[1],\n\t\t\t\tPRE_CONDITIONS = content[ind].split('\\t')[2],\n\t\t\t\tPRECEDENCE = content[ind].split('\\t')[3],\n\t\t\t\tCOMPLEXITY = content[ind].split('\\t')[4],\n\t\t\t\tPRE_CON_COUNT = content[ind].split('\\t')[5],\n\t\t\t\tWEIGHTAGE = content[ind].split('\\t')[6],\n\t\t\t\tDIFF = content[ind].split('\\t')[7]\n\t\t\t)\n\t\t\tdata.append(record)\n\treturn data\n\ndef psoResult(request):\n\twith open(os.path.join(BASE_PATH, 'result.json'), 'r') as file:\n\t\tjsonContent = JSON.load(file)\n\n\tdata = extractDataFromFile('PSO Result.tsv')\n\tresponseObj = {\n\t\t\"PSO\": jsonContent['PSO'],\n\t\t\"x_axis\": jsonContent['PSO']['x_axis'],\n\t\t\"y_axis\": jsonContent['PSO']['y_axis'],\n\t\t\"data\": data\n\t}\n\treturn render(request, \"pso result.htm.j2\", JSON.loads(JSON.dumps(responseObj)))\n\ndef gaResult(request):\n\twith open(os.path.join(BASE_PATH, 'result.json'), 'r') as file:\n\t\tjsonContent = JSON.load(file)\n\n\tdata = extractDataFromFile('GA Result.tsv')\n\tresponseObj = {\n\t\t\"GA\": jsonContent['GA'],\n\t\t\"x_axis\": jsonContent['GA']['x_axis'],\n\t\t\"y_axis\": jsonContent['GA']['y_axis'],\n\t\t\"data\": data\n\t}\n\treturn render(request, \"ga result.htm.j2\", JSON.loads(JSON.dumps(responseObj)))\n\ndef compareResult(request):\n\twith open(os.path.join(BASE_PATH, 'result.json'), 'r') as file:\n\t\tjsonContent = JSON.load(file)\n\treturn render(request, \"compare.htm.j2\", jsonContent)\n\ndef psoSuite(request):\n\tdata = extractDataFromFile('PSO Result.tsv')\n\treturn render(request, \"pso suite.htm.j2\", { \"data\": data, \"title\": \"PSO test suite\" })\n\ndef gaSuite(request):\n\tdata = extractDataFromFile('GA Result.tsv')\n\treturn render(request, \"ga suite.htm.j2\", { \"data\": data, \"title\": \"GA test suite\" })","repo_name":"datmemerboi/Test-Case-Optimization","sub_path":"TCO_root/result/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"23193913752","text":"# grab AA info from ECCC website and dump into spreadsheet\nimport requests\nimport json\nimport pprint\nimport csv\n\nurl = \"https://api-melupufoagt.stackpathdns.com/api/space_orders\"\n\nheaders = {\"Accept\": \"application/json\"}\n\nquery = {\n \"specials\": 1,\n \"key\": \"c2bc1038-e140-493e-8316-93d221b76847\",\n \"category\": \"13504\"\n}\n\nresponse = requests.request(\n \"GET\",\n url,\n headers=headers,\n params=query\n)\n\nartist_alley = []\n\nAA_all_info = response.json()[\"space_orders\"]\n\nfor artist in AA_all_info:\n vendor = {}\n vendor.update({\n \"Company\": artist[\"company\"],\n \"First Name\": artist[\"first_name\"],\n \"Last Name\": artist[\"last_name\"],\n \"Table\": artist[\"booth\"],\n \"Website\": artist[\"website\"]\n })\n artist_alley.append(vendor)\n\nwith open(\"ECCC_AA.csv\", \"w\") as eccc_aa_csv:\n artist_writer = csv.writer(eccc_aa_csv)\n\n count = 0\n\n for artist in artist_alley:\n if count == 0:\n header = artist.keys()\n artist_writer.writerow(header)\n count += 1\n\n artist_writer.writerow(artist.values())\n","repo_name":"danicolman/comic_con_scrapes","sub_path":"ECCC_AA.py","file_name":"ECCC_AA.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"23862715096","text":"nums = [2,0,2,1,1,0]\n# red = 0\n# white = 0\n# blue = 0\n\n# for i in nums:\n# if i == 0:\n# red += 1\n# elif i == 1:\n# white += 1\n# elif i == 2:\n# blue += 1\n\n# for i in range(0, len(nums)):\n# if i < red:\n# nums[i] = 0\n# elif i >= red and i < red + white:\n# nums[i] = 1\n# else:\n# nums[i] = 2\n\nleft = 0\nright = len(nums) - 1\ni = 0\nwhile i <= right:\n if nums[i] == 0:\n temp = nums[left]\n nums[left] = nums[i]\n nums[i] = temp\n left += 1\n i += 1\n elif nums[i] == 2:\n temp = nums[right]\n nums[right] = nums[i]\n nums[i] = temp\n right -= 1\n else:\n i += 1\nprint(nums)\n","repo_name":"Sweetyxz/leetcode","sub_path":"075.py","file_name":"075.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26250856661","text":"pacientes=[]\nidades=[]\nenderecos=[]\nsuspeita_covid=[]\nresposta=\"S\"\n\nwhile resposta== \"S\":\n pacientes.append(input(\"Nome do paciente: \"))\n idades.append(int(input(\"Idade: \")))\n enderecos.append(input(\"Endereço: \"))\n suspeita_covid.append(input(\"Paciente tem alguma suspeita de covid19: \"))\n resposta=input(\"Digite \\\"S\\\" para continuar ou digite \\\"N\\\" para sair\\n\") .upper()\n # \\\"S\\\" é usado para que não entenda somente como texto\n if resposta== \"N\":\n print(\"Até logo!!\")\n\n for indice in range (0,len(pacientes)):\n print(\"\\nPaciente...:\", pacientes[indice])\n print(\"Idade......:\", idades[indice])\n print(\"Endereço...:\", enderecos[indice])\n print(\"Com covid..:\", suspeita_covid[indice])\n\n\n","repo_name":"MarcosPontes136/Conceitos_Python","sub_path":"venv/VARIAVEIS_LISTA/MULTIPLAS_LISTAS_E_INDICES.py","file_name":"MULTIPLAS_LISTAS_E_INDICES.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5749726435","text":"# Picks\nP = [' ',' ',' ',' ',' ',' ',' ',' ',' ']\n# Picks Reset\n# Preset = [' ',' ',' ',' ',' ',' ',' ',' ',' ']\n\ndef gridReset():\n\tfor i in range(len(P)):\n\t\tP[i] = ' '\n\n# Turn counter (max turns = 9. if 9 tiebreak)\ncount = [0]\n\n# Turn counter\ndef add():\n\tcount[0] += 1\n\n# Current Grid showing picks\ndef display_board():\n print('{n7}|{n8}|{n9}\\n------\\n{n4}|{n5}|{n6}\\n------\\n{n1}|{n2}|{n3}'.format(n1=P[0],n2=P[1],n3=P[2],n4=P[3],n5=P[4],n6=P[5],n7=P[6],n8=P[7],n9=P[8]))\n #print(show)\n\n\ndef runTicTacToe():\n\trestart = True\n\n\twhile restart == True:\n\t\tbegin = start()\n\n\t\tif begin == False:\n\t\t\trestart = False\n\t\t\tbreak\n\n\t\t# P = Preset\n\t\tgridReset()\n\t\tcount[0] = 0\n\n\n#Start the game!\ndef start():\n p1=''\n p2=''\n\n\n print('\\n Playing TicTacToe!\\nPlease use the num pad grid system as guide\\n')\n display_board()\n\n playersPicked = False\n\n while playersPicked == False:\n \tinitial = input('\\nPick character: X or O: ')\n\n \tp1 = initial.upper()\n\n \tif p1 == 'X':\n \t\tp2 = 'O'\n \t\tplayersPicked = True\n \tif p1 == 'O':\n \t\tp2 = 'X'\n \t\tplayersPicked = True\n\n print(f'\\nplayer 1 is {p1} | player 2 is {p2}\\n')\n\n result = player_turns(p1,p2)\n\n if result == True:\n \tgameTie()\n else:\n \tshowWinner(result)\n\n if_replay = play_again()\n\n if if_replay == True:\n \treturn True\n else:\n \treturn False\n\n\n\n#alternate between players to pick X or O until tie or win\n#returns [1] or [2] or True. True = tie\ndef player_turns(p1,p2):\n\tplay = True\n\tswitch_turn = True\n\twinner = []\n\ttie = False\n\n\twhile play == True:\n\n\t\twhile switch_turn == True:\n\t\t\tplayer_turn = pick(p1)\n\t\t\tres = pick_complete(player_turn)\n\t\t\t#print(f\"\\nplayerturn: {player_turn} \\nres: {res}\")\n\n\t\t\tif res != True:\n\t\t\t\tprint('ERROR! pick_complete FALSE player 1')# chnage this to error restart\n\n\t\t\tmatch = check_for_match()\n\t\t\tif match == True:\n\t\t\t\tifwinner = haswon(1)\n\t\t\t\twinner.append(1)\n\t\t\t\tplay = False\n\t\t\t\tbreak\n\t\t\tswitch_turn = False\n\n\t\tifTie = tiebreak()\n\t\tif ifTie == True:\n\t\t\tplay = False\n\t\t\ttie = True\n\t\t\tdisplay_board()\n\t\t\tbreak\n\n\t\twhile switch_turn == False:\n\t\t\tplayer_turn = pick(p2)\n\t\t\tres = pick_complete(player_turn)\n\n\t\t\tif res != True:\n\t\t\t\tprint('ERROR! pick_complete FALSE player 2')\n\n\t\t\tif match == True:\n\t\t\t\thaswon(2)\n\t\t\t\twinner.append(2)\n\t\t\t\tplay = False\n\t\t\t\tbreak\n\t\t\tswitch_turn = True\n\n\t#returns winner number\n\tif play == False:\n\t\tprint('\\nTHE GAME HAS BEEN PLAYED!\\n')\n\t\treturn winner\n\n\t#if tie break\n\tif tie == True:\n\t\treturn True\n\n\n#player picks position on grid. if successful return true\ndef pick(p):\n\tcompleted = False\n\n\twhile completed == False:\n\t\tpicked = input(p + ' | pick number 1-9: ')\n\t\tpick = int(picked)\n\t\tprint(f\"\\n\\nPICK: {pick}\\n\\n\")\n\n\t\tif pick > 10:\n\t\t\tprint('Pick number between 1-9: ')\n\t\t\tbreak\n\n\t\tt = pick - 1\n\n\t\tif P[t] == ' ':\n\t\t\tP[t] = p\n\t\t\tcompleted = True\n\n\tif completed == True:\n\t\treturn True\n\n\n#add to count, display_board() and switch if pick made\ndef pick_complete(player_turn):\n\tif player_turn == True:\n\t\tadd()\n\t\tdisplay_board()\n\t\treturn True\n\treturn False\n\n\ndef check_for_match():\n## MAKE SURE THIS WORKS - just copied and pasted in\n#THEN CHECK FOR TIE\n#THEN sort out if there was a winner\n win_combo = [ [6,3,0], [7,4,1], [8,5,3], [8,4,0], [6,7,8], [3,4,5], [0,1,2], [6,4,2] ]\n\n Xwin = ['X', 'X', 'X']\n Owin = ['O','O','O']\n\n winner = False\n\n for i in range(len(win_combo)):\n\n check = []\n\n for y in win_combo[i]:\n if P[y] == 'X' or P[y] == 'O':\n check.append(P[y])\n if check == Xwin or check == Owin:\n winner = True\n\n return winner == True\n\n\n#if a player has 3 in a row\ndef haswon(num):\n\tprint(f\"*** Player {num} has WON! ***\")\n\treturn True\n\n\n# check all moves amde\ndef tiebreak():\n\tif count[0] == 9:\n\t\treturn True\n\n\n#print Game has finished in tie\ndef gameTie():\n\tprint(\"\\n***\\nTIS A TIE!\\n***\\n\")\n\n\n#print winning statement\ndef showWinner(res):\n\tplayer = ''\n\tif res[0] == 1:\n\t\tplayer = 1\n\telse:\n\t\tplayer = 2\n\tprint(f\"\\n*****\\nPLayer {player} has WON!!!\\n***\\n\")\n\n\n# ask if user wants to restart game. return true or false\ndef play_again():\n\ttoPlayy = input(\"\\nThanks for playing. Would you like to play agin? (Y/N)\")\n\tshould_play = toPlayy.upper()\n\n\tif should_play == 'Y':\n\t\treturn True\n\telse:\n\t\treturn False\n\n\n\nrunTicTacToe()\n","repo_name":"hitesh-92/TicTacToe","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"7268855696","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\nxx=[]\nyy=[]\nlamd=0.7\nz=30\nk=0.00009\nx=math.pow( 1+k, z )\nmonth=20\nn = np.arange(1, month*12, 1)\na0=5.9\ndit=5.9\ncard=[]\nbk=0.000003/365\nbx=math.pow( 1+bk, z )\nfor i in n:\n un=a0*math.pow(x,i)+lamd*((1-math.pow(x,i-1))/(1-x))\n xx.append(i)\n yy.append(un)\n dit = a0 * math.pow(bx, i) + lamd * ((1 - math.pow(bx, i - 1)) / (1 - bx))\n card.append(dit)\nstr=\"1/10000=\"+str((k*10000))+\",invest/month=\"+str(lamd*10000)+\",count=\"+str(month)+\"years\\ntotal rmb=\"+str(yy[len(yy)-1])\nplt.title(str)\nplt.plot(xx, yy, label=\"yu e bao\")\nplt.plot(xx,card,label=\"bank\",linestyle = \"--\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.ylim(0, yy[len(yy)-1]+30)\nplt.legend()\nplt.show()\n","repo_name":"tianjingle/think","sub_path":"src/dingtoufuli.py","file_name":"dingtoufuli.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39938418719","text":"cond = [int(n) for n in input().split( )]\nnums = [int(n) for n in input().split( )]\nm = cond[1]\nwhile m:\n cmd = [int(n) for n in input().split( )]\n op = cmd[0]\n l = cmd[1]\n r = cmd[2]\n temp1 = nums[0:l-1]\n temp2 = nums[l-1:r]\n temp3 = nums[r:]\n if op == 0:\n temp2.sort()\n else:\n temp2.sort(reverse=True)\n nums = temp1+temp2+temp3\n m -= 1\nq = int(input())\nprint(nums[q-1])\n","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2387/60737/251981.py","file_name":"251981.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"11956167249","text":"class Node():\n def __init__(self,data):\n self.data=data\n self.next=None\n\nclass Queue():\n def __init__(self):\n self.first=None\n self.last=None\n self.length=0\n\n def enqueue(self,node):\n node=Node(node)\n if self.first is None:\n self.first=node\n self.last=node\n self.length+=1\n else:\n self.last.next=node\n self.last=node\n self.length+=1\n\n def peek(self):\n return self.first.data\n\n def dequeue(self):\n z=self.first\n self.first=None\n self.first=z.next\n self.length-=1\n return z\n \n def lookup(self,value):\n node = self.first\n while node is not None and node.data!=value:\n node=node.next\n return node is not None\n\n def printQueue(self):\n node=self.first\n while node is not None:\n print(node.data,\"--> \",end=\"\")\n node=node.next\n print(None)\n \ns = Queue()\n\ns.enqueue(4)\ns.enqueue(8)\ns.enqueue(12)\ns.enqueue(20)\ns.dequeue()\ns.printQueue()","repo_name":"BanateanuRazvan/Python-Problems","sub_path":"Queues/Queues.py","file_name":"Queues.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"25112897884","text":"import requests\nfrom pathlib import Path\nimport configparser\nimport pytest\nimport logging\nimport os\nfrom datetime import datetime\nfrom enum import Enum\n\npath = Path(__file__)\nos.chdir(\"C:/Users/User/PycharmProjects/pythonUI1/utils\")\nconfig_path = os.path.join(\"setting.ini\")\nconfig = configparser.ConfigParser()\nconfig.read(config_path, encoding='utf-8-sig')\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.hookimpl\ndef pytest_runtest_setup(item):\n logging_plugin = item.config.pluginmanager.get_plugin(\"logging-plugin\")\n timestamp = datetime.strftime(datetime.now(), '[%Y-%m-%d]__%H-%M-%S')\n os.chdir(\"C:/Users/User/PycharmProjects/pythonUI1/\")\n logging_plugin.set_log_path(os.path.join('logger', f'{item.name}__{timestamp}.log'))\n\n\nPOST_REGISTER_DASHBOARD = 'dashboard'\nPOST_REGISTER_WIDGET = 'widget'\n\n\nclass TypeWidgetApi(Enum):\n Launch_statistics_chart = 'statisticTrend'\n OVERALL_STSTISTICS = 'overallStatistics'\n\n\nclass NameFilterApi(Enum):\n filter_sorted_by_start_time = 245\n filter_sorted_by_launch_name = 244\n filter_filter_sorted_by_total = 246\n\n\nclass ApiDashboard:\n def __init__(self, name):\n self.name = name\n\n\nclass ApiWidget:\n def __init__(self, name, widgetType, filterIds):\n self.name = name\n self.widgetType = widgetType\n self.filterIds = filterIds\n self.share = \"false\"\n\n\nclass Api:\n def __init__(self):\n self.url = f\"{config.get('Settings', 'uri_api')}\"\n self.project_name = f\"{config.get('Settings', 'projectName')}\"\n self.access_token = config.get('Settings', 'access_token')\n\n def create_api_dashboard(self, ApiDashboard):\n body = {\"description\": '',\n \"name\": ApiDashboard.name,\n \"share\": 'False'}\n response_api = requests.post(f'{self.url}{self.project_name}{POST_REGISTER_DASHBOARD}', json=body,\n headers={'Authorization': self.access_token})\n logger.info(response_api.json())\n return response_api\n\n def create_api_widget(self, ApiWidget):\n body = {\n \"contentParameters\": {\n \"contentFields\": [\n \"statistics$executions$total\",\n \"statistics$executions$passed\",\n \"statistics$executions$failed\",\n \"statistics$executions$skipped\",\n \"statistics$defects$product_bug$pb001\",\n \"statistics$defects$automation_bug$ab001\",\n \"statistics$defects$system_issue$si001\",\n \"statistics$defects$no_defect$nd001\",\n \"statistics$defects$to_investigate$ti001\"\n ],\n \"itemsCount\": 50,\n \"widgetOptions\": {\n \"zoom\": \"false\",\n \"timeline\": \"launch\",\n \"viewMode\": \"area-spline\"\n }\n },\n \"description\": \"\",\n \"filterIds\": [ApiWidget.filterIds],\n \"name\": ApiWidget.name,\n \"share\": \"false\",\n \"widgetType\": ApiWidget.widgetType\n }\n response_api = requests.post(f'{self.url}{self.project_name}{POST_REGISTER_WIDGET}', json=body,\n headers={'Authorization': self.access_token})\n logger.info(response_api.json())\n return response_api\n\n def add_widget_to_specified_dashboard(self, id_dashboard, id_widget):\n body = {\"addWidget\": {\n \"share\": \"true\",\n \"widgetId\": id_widget,\n \"widgetName\": \"\",\n \"widgetOptions\": {\n \"zoom\": \"false\",\n \"timeline\": \"launch\",\n \"viewMode\": \"area-spline\"},\n \"widgetPosition\": {\n \"positionX\": 0,\n \"positionY\": 0\n },\n \"widgetSize\": {\n \"height\": 5,\n \"width\": 5\n },\n \"widgetType\": \"statisticTrend\"\n }\n }\n response_api = requests.put(f'{self.url}{self.project_name}{POST_REGISTER_DASHBOARD}/{id_dashboard}/add',\n json=body, headers={'Authorization': self.access_token})\n logger.info(response_api.json())\n return response_api\n\n def delete_api_dashboard(self, id_dashboard):\n requests.delete(f'{self.url}{self.project_name}{POST_REGISTER_DASHBOARD}/{id_dashboard}',\n headers={'Authorization': self.access_token})\n\n def add_api_test_run(self):\n body = {\"createDashboard\": 'true'}\n response_api = requests.post(f'{self.url}demo/{self.project_name}', json=body,\n headers={'Authorization': self.access_token})\n logger.info(response_api.json())\n return response_api\n\n def get_widget_by_id(self, id_widget):\n response_api = requests.get(f'{self.url}{self.project_name}{POST_REGISTER_WIDGET}/{id_widget}', headers={'Authorization': self.access_token})\n logger.info(response_api.json())\n return response_api\n\n def get_dashboard_by_id(self, id_dashboard):\n response_api = requests.get(f'{self.url}{self.project_name}{POST_REGISTER_DASHBOARD}/{id_dashboard}', headers={'Authorization': self.access_token})\n logger.info(response_api.json())\n return response_api\n#wwwwwww\n#rrrr","repo_name":"ilyaitos/Ui_test","sub_path":"test_api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"8632220143","text":"#euler tour / + bottom up segement tree\nimport sys\nsys.setrecursionlimit(200001)\nN=int(input())\n\nli=[[] for _ in range(100001)]\n\nfor i in range(N-1):\n v1,v2=map(int,sys.stdin.readline().split())\n li[v1].append(v2)\n li[v2].append(v1)\n\nseg=[[0]*200001 for i in range(20)]\nindex=[0]*100001\nhe=[0]*100001\nx=0\ndef tour(v,p,h):\n global x\n seg[0][x]=v\n index[v]=x\n he[v]=h\n x+=1\n for i in li[v]:\n if i==p:\n continue\n tour(i,v,h+1)\n seg[0][x] = v\n x += 1\ntour(1,0,0)\n\ni=1\nwhile seg[i-1][0]:\n j=0\n while seg[i-1][j] and seg[i-1][j+2**(i-1)]:\n if he[seg[i-1][j]] he[seg[j][cur]]:\n ans=seg[j][cur]\n cur+=2**(j)\n dif = dif >> 1\n j+=1\n print(ans)\n","repo_name":"mm0133/BOJ_problems","sub_path":"11438 LCA2.py","file_name":"11438 LCA2.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"8291079819","text":"# https://leetcode-cn.com/problems/coin-change/\n\n# 按背包问题做,一次只下降一个coin的值\n# 按深度优先搜索做,一次尽可能高的下降,所以第一次达成目标的时候就是找到了最少组合了\n\n# Runtime: 1268 ms (64%)\nfrom functools import lru_cache\n\nclass Solution:\n def coinChange(self, coins, amount):\n\n coins = sorted(coins, key=lambda x: -x)\n\n @lru_cache(None)\n def recur(amount):\n if amount == 0: return 0\n if amount in coins: return 1\n\n ans = 10000000007\n for coin in coins:\n if amount > coin: ans = min(ans, recur(amount - coin)) \n return ans + 1\n\n ans = recur(amount)\n\n return ans if ans != 10000000008 else -1\n\n# Runtime: 64 ms (100%)\nimport math\n\nclass Solution:\n def coinChange(self, coins, amount):\n n = len(coins)\n coins.sort(reverse=True) # 先给硬币排序,降序\n self.res = float(\"inf\") # 定义最小的使用硬币的数量为self.res\n\n def dfs(index,target,count): # 定义深度优先搜索算法——>目标下降的速度更快\n coin = coins[index]\n print(f'index: {index}; coin: {coin}; target: {target}; count: {count}')\n if math.ceil(target / coin) + count >= self.res:\n return\n if target % coin == 0:\n self.res = count + target // coin\n return\n if index == n - 1:\n return\n for j in range(target // coin, -1, -1):\n dfs(index + 1,target - j * coin, count + j)\n\n dfs(0, amount, 0)\n return int(self.res) if self.res != float(\"inf\") else -1\n\n\ncoins = [1, 2, 5]; amount = 11\n# coins = [2]; amount = 3\n# coins = [1]; amount = 0\n# coins = [1]; amount = 1\n# coins = [1]; amount = 2\n\ns = Solution()\nprint(s.coinChange(coins, amount))","repo_name":"Wenzhi-Ding/coding_notes","sub_path":"10_LeetCode/L0322-coin-change.py","file_name":"L0322-coin-change.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"80"} +{"seq_id":"1341497008","text":"import argparse\nimport logging\nimport logging.handlers\nimport os\nimport sys\nfrom collections import defaultdict\n\nfrom hived.log import JsonFormatter\nfrom hived.conf import LOG_TO_CONSOLE, LOG_TO_FILE, CONSOLE_LOGLEVEL\n\n_name = None\n\n_LOG_LEVELS = defaultdict(lambda: logging.INFO)\n\n_LOG_LEVELS[\"INFO\"] = logging.INFO\n_LOG_LEVELS[\"ERROR\"] = logging.ERROR\n_LOG_LEVELS[\"DEBUG\"] = logging.DEBUG\n\n\ndef get_name():\n return _name\n\n\ndef get_logging_handlers(process_name):\n \"\"\"Returns a list of logging handlers, each with their level already set\"\"\"\n\n loggers = []\n if LOG_TO_CONSOLE:\n std_out = logging.StreamHandler(sys.stdout)\n std_out.setLevel(_LOG_LEVELS[CONSOLE_LOGLEVEL])\n loggers.append(std_out)\n\n if LOG_TO_FILE:\n path = os.path.expanduser('~/logs')\n if not os.path.isdir(path):\n os.mkdir(path)\n rotating_file = logging.handlers.RotatingFileHandler('%s/%s.log' % (path, process_name), maxBytes=10000000,\n backupCount=10, encoding='utf-8')\n rotating_file.setLevel(logging.INFO)\n loggers.append(rotating_file)\n\n return loggers\n\n\ndef configure_logging(process_name, handlers):\n # Leaving this here because it is the only piece code currently being called by all processes\n global _name\n _name = process_name\n\n root = logging.getLogger('root')\n root.setLevel(logging.NOTSET)\n root.addHandler(logging.NullHandler())\n\n logger = logging.getLogger(process_name)\n logger.setLevel(logging.DEBUG)\n logger.propagate = False\n\n formatter = JsonFormatter()\n for handler in handlers:\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n return logger\n\n\nclass Process(object):\n _created = False\n name = None\n worker_class = None\n default_workers = 1\n default_queue_name = None\n\n def __new__(cls, *args):\n if cls._created:\n raise RuntimeError('%s instance already created' % cls.__name__)\n\n cls._created = True\n return object.__new__(cls, *args)\n\n def get_arg_parser(self):\n parser = argparse.ArgumentParser(description='Start %s' % self.name)\n parser.add_argument('-w', '--workers', type=int, default=self.default_workers,\n help='Number of worker threads to run')\n parser.add_argument('-q', '--queue', default=self.default_queue_name or self.name, help='queue name')\n return parser\n\n def get_logging_handlers(self):\n return get_logging_handlers(self.name)\n\n def configure_logging(self):\n return configure_logging(self.name, self.get_logging_handlers())\n\n def create_worker(self, args, logger):\n return self.worker_class(logger, queue_name=args.queue, process=self)\n\n def run(self):\n arg_parser = self.get_arg_parser()\n args = arg_parser.parse_args()\n logger = self.configure_logging()\n for i in range(args.workers):\n self.create_worker(args, logger).start()\n","repo_name":"sievetech/hived","sub_path":"hived/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"51046582725","text":"from django.core.management.base import BaseCommand\r\nfrom django.core import management\r\nfrom django.conf import settings\r\nimport sys\r\nimport os\r\nimport datetime\r\nfrom backup_ftp.utils import archive_file\r\nfrom backup_ftp.ftp import FTP_backup\r\nimport re\r\n\r\n\r\nclass Command(BaseCommand):\r\n\r\n def handle(self, *args, **options):\r\n BASE_DIR = os.path.abspath(os.path.dirname(__name__))\r\n FTP_HOST = settings.FTP_BACKUP_HOST\r\n FTP_PORT = settings.FTP_BACKUP_PORT\r\n FTP_USER = settings.FTP_BACKUP_USER\r\n FTP_PASSWORD = settings.FTP_BACKUP_PASSWORD\r\n FTP_FILES_COUNT = settings.FTP_BACKUP_FILES_COUNT\r\n FTP_USE_TLS = settings.FTP_BACKUP_USE_TLS\r\n FTP_DIR = settings.FTP_DIR\r\n\r\n path = os.path.join(BASE_DIR, 'backups')\r\n\r\n if not os.path.exists(path):\r\n os.mkdir(path, 0o755)\r\n\r\n date = datetime.datetime.now()\r\n file = 'fulldump' + date.strftime('%Y%m%d%H%M') +'.json'\r\n json_src = os.path.join(path, file)\r\n\r\n with open(json_src, 'w') as f:\r\n management.call_command('dumpdata', indent=2, stdout=f)\r\n\r\n archive_path = archive_file(json_src)\r\n\r\n ftp = FTP_backup(host=FTP_HOST, port=FTP_PORT, use_tls=FTP_USE_TLS)\r\n if ftp.connect(timeout=10) and ftp.login(user=FTP_USER, password=FTP_PASSWORD):\r\n ftp.open_dir(FTP_DIR)\r\n ftp.upload_file(archive_path)\r\n files_list = ftp.list_files()\r\n if len(files_list) > FTP_FILES_COUNT:\r\n for index, item in enumerate(files_list):\r\n file_attrs = re.split(r'\\s+', item)\r\n date_str = file_attrs[0] + ' ' + file_attrs[1]\r\n file_name = file_attrs[-1]\r\n date = datetime.datetime.strptime(date_str, '%m-%d-%y %I:%M%p')\r\n file_attrs = {'date': date, 'file': file_name}\r\n files_list[index] = file_attrs\r\n files_list = sorted(files_list, key = lambda i: i['date'], reverse=True)\r\n for item in files_list[FTP_FILES_COUNT:]:\r\n ftp.delete_file(item['file'])\r\n ftp.quit()\r\n if os.path.exists(json_src):\r\n os.remove(json_src)\r\n if os.path.exists(archive_path):\r\n os.remove(archive_path)\r\n\r\n\r\n\r\n\r\n","repo_name":"hitnik/django_backup_ftp","sub_path":"management/commands/dumpdata_ftp.py","file_name":"dumpdata_ftp.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"10830840629","text":"import copy\nfrom typing import Any, Dict, Optional, Union\n\nimport pandas as pd\n\nfrom ambrosia import types\nfrom ambrosia.tools.ab_abstract_component import AbstractFittableTransformer\nfrom ambrosia.tools.back_tools import wrap_cols\n\n\nclass AggregatePreprocessor(AbstractFittableTransformer):\n \"\"\"\n Preprocessing class for data aggregation.\n\n Can group data by multiple columns and aggregate it using methods\n for real and categorial features.\n\n Parameters\n ----------\n categorial_method : types.MethodType, default: ``\"mode\"``\n Aggregation method for categorial variables that\n will become as a default behavior.\n real_method : types.MethodType, default: ``\"sum\"``\n Aggregation method for real variables that\n will become as a default behavior.\n\n Attributes\n ----------\n categorial_method : types.MethodType\n Default aggregation method for categorial variables.\n real_method : types.MethodType\n Default aggregation method for real variables.\n groupby_columns : types.ColumnNamesType\n Columns which were used for groupping in the last aggregation.\n Gets value after fitting the class instance.\n agg_params : Dict\n Dictionary with aggregation rules which was used in the last\n aggregation.\n Gets value after fitting the class instance.\n \"\"\"\n\n @staticmethod\n def __mode_calculation(values: pd.Series) -> Any:\n \"\"\"\n Mode function for aggregation.\n \"\"\"\n return values.value_counts().index[0]\n\n @staticmethod\n def __simple_agg(values: pd.Series) -> Any:\n \"\"\"\n Simple aggregation, just picks the first element.\n \"\"\"\n return values.iloc[0]\n\n @staticmethod\n def __transform_agg_param(aggregation_method: types.MethodType) -> types.MethodType:\n \"\"\"\n Invoke an aggregation callable function by given string alias.\n \"\"\"\n if aggregation_method == \"mode\":\n return AggregatePreprocessor.__mode_calculation\n if aggregation_method == \"simple\":\n return AggregatePreprocessor.__simple_agg\n return aggregation_method\n\n @staticmethod\n def __transform_params(dataframe: pd.DataFrame, aggregation_params: Dict) -> Dict:\n \"\"\"\n Iteratively apply transformations specified by aggragation parameters.\n \"\"\"\n agg_params = copy.deepcopy(aggregation_params)\n for column, method in agg_params.items():\n if column not in dataframe.columns:\n raise ValueError(f\"{column} does not exist in the dataframe!\")\n agg_params[column] = AggregatePreprocessor.__transform_agg_param(method)\n return agg_params\n\n def __init__(self, categorial_method: types.MethodType = \"mode\", real_method: types.MethodType = \"sum\"):\n self.categorial_method = categorial_method\n self.real_method = real_method\n self.agg_params = None\n self.groupby_columns = None\n super().__init__()\n\n def __real_case_step(\n self,\n agg_params: Optional[Dict] = None,\n real_cols: Optional[types.ColumnNamesType] = None,\n ) -> None:\n \"\"\"\n A private method containing aggregation parameters filling logic\n for real metrics.\n \"\"\"\n real_cols = wrap_cols(real_cols)\n for real_feature in real_cols:\n agg_params[real_feature] = self.real_method\n\n def __categorial_case_step(\n self,\n agg_params: Optional[Dict] = None,\n categorial_cols: Optional[types.ColumnNamesType] = None,\n ) -> None:\n \"\"\"\n A private method containing aggregation parameters filling logic\n for categorial metrics.\n \"\"\"\n categorial_cols = wrap_cols(categorial_cols)\n for categorial_feature in categorial_cols:\n agg_params[categorial_feature] = self.categorial_method\n\n def __empty_args_step(\n self,\n agg_params: Optional[Dict] = None,\n real_cols: Optional[types.ColumnNamesType] = None,\n categorial_cols: Optional[types.ColumnNamesType] = None,\n ) -> None:\n \"\"\"\n A private method containing aggregation parameters filling logic\n if no aggregation parameters passed.\n \"\"\"\n if real_cols is not None:\n self.__real_case_step(agg_params, real_cols)\n if categorial_cols is not None:\n self.__categorial_case_step(agg_params, categorial_cols)\n\n def get_params_dict(self) -> Dict:\n \"\"\"\n Returns dictionary with parameters of the last run() or transform() call.\n \"\"\"\n self._check_fitted()\n return {\"aggregation_params\": self.agg_params, \"groupby_columns\": self.groupby_columns}\n\n def load_params_dict(self, params: Dict) -> None:\n \"\"\"\n Load prefitted parameters form a dictionary.\n\n Parameters\n ----------\n params : Dict\n Dictionary with prefitted params.\n \"\"\"\n if \"groupby_columns\" in params:\n self.groupby_columns = params[\"groupby_columns\"]\n else:\n raise TypeError(f\"params argument must contain: {'column_names'}\")\n if \"aggregation_params\" in params:\n self.agg_params = params[\"aggregation_params\"]\n else:\n raise TypeError(f\"params argument must contain: {'aggregation_params'}\")\n self.fitted = True\n\n def fit(\n self,\n dataframe: pd.DataFrame,\n groupby_columns: types.ColumnNamesType,\n agg_params: Optional[Dict] = None,\n real_cols: Optional[types.ColumnNamesType] = None,\n categorial_cols: Optional[types.ColumnNamesType] = None,\n ) -> pd.DataFrame:\n \"\"\"\n Fit preprocessor with parameters of aggregation.\n\n Aggregation will be performed using passed dictionary with\n defined aggregation conditions for each columns of interest,\n or lists of columns with default class aggregation behavior.\n\n Parameters\n ----------\n dataframe : pd.DataFrame\n Table with selected columns.\n groupby_columns : types.ColumnNamesType\n Columns for GROUP BY.\n agg_params : Dict, optional\n Dictionary with aggregation parameters.\n real_cols : types.ColumnNamesType, optional\n Columns with real metrics.\n Overriden by ``agg_params`` parameter and could be passed if\n expected default aggregation behavior.\n categorial_cols : types.ColumnNamesType, optional\n Columns with categorial metrics\n Overriden by ``agg_params`` parameter and could be passed if\n expected default aggregation behavior.\n\n Returns\n -------\n self : object\n Instance object.\n \"\"\"\n if agg_params is None and real_cols is None and categorial_cols is None:\n raise ValueError(\"Set agg_params or pass real_cols and categorial_cols\")\n if agg_params is None:\n agg_params = {}\n self.__empty_args_step(agg_params, real_cols, categorial_cols)\n self._check_cols(dataframe, agg_params.keys())\n self.groupby_columns = groupby_columns\n self.agg_params = copy.deepcopy(agg_params)\n self.fitted = True\n return self\n\n def transform(\n self,\n dataframe: pd.DataFrame,\n ) -> pd.DataFrame:\n \"\"\"\n Apply table transformation by its aggregation with prefitted\n parameters.\n\n Parameters\n ----------\n dataframe : pd.DataFrame\n Table to aggregate.\n\n Returns\n -------\n agg_table : pd.DataFrame\n Aggregated table.\n \"\"\"\n self._check_fitted()\n self._check_cols(dataframe, self.agg_params.keys())\n agg_params = AggregatePreprocessor.__transform_params(dataframe, self.agg_params)\n return dataframe.groupby(self.groupby_columns, as_index=False).agg(agg_params)\n\n def fit_transform(\n self,\n dataframe: pd.DataFrame,\n groupby_columns: types.ColumnNamesType,\n agg_params: Optional[Dict] = None,\n real_cols: Optional[types.ColumnNamesType] = None,\n categorial_cols: Optional[types.ColumnNamesType] = None,\n ) -> pd.DataFrame:\n \"\"\"\n Fit preprocessor parameters using given dataframe and aggregate it.\n\n Parameters\n ----------\n dataframe : pd.DataFrame\n Table to aggregate.\n groupby_columns : types.ColumnNamesType\n Columns for GROUP BY.\n agg_params : Dict, optional\n Dictionary with aggregation parameters.\n real_cols : types.ColumnNamesType, optional\n Columns with real metrics.\n Overriden by ``agg_params`` parameter and could be passed if\n expected default aggregation behavior.\n categorial_cols : types.ColumnNamesType, optional\n Columns with categorial metrics\n Overriden by ``agg_params`` parameter and could be passed if\n expected default aggregation behavior.\n\n Returns\n -------\n agg_table : pd.DataFrame\n Aggregated table.\n \"\"\"\n self.fit(dataframe, groupby_columns, agg_params, real_cols, categorial_cols)\n return self.transform(dataframe)\n","repo_name":"MobileTeleSystems/Ambrosia","sub_path":"ambrosia/preprocessing/aggregate.py","file_name":"aggregate.py","file_ext":"py","file_size_in_byte":9299,"program_lang":"python","lang":"en","doc_type":"code","stars":200,"dataset":"github-code","pt":"80"} +{"seq_id":"24381000000","text":"from typing import List, Optional\n\nfrom pydantic import ConfigDict, BaseModel\n\nclass CodeFramePydantic(BaseModel):\n df_path: str\n context_columns: List\n embeddable_columns: List\n embedding_columns: List\n name: str\n save_path: Optional[str]\n save_dir: str\n markdown: str\n model_config = ConfigDict(arbitrary_types_allowed=True)\n\n\nclass MemoryFramePydantic(BaseModel):\n df_path: str\n context_columns: List[str]\n embeddable_columns: List[str]\n embedding_columns: List[str]\n time_series_columns: List[str]\n name: str\n save_path: Optional[str]\n save_dir: str\n markdown: str\n model_config = ConfigDict(arbitrary_types_allowed=True)","repo_name":"Neural-Dragon-AI/BabyDragon","sub_path":"babydragon/memory/frames/frame_models.py","file_name":"frame_models.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"12453903239","text":"def solution(n, edge):\n answer = 0\n visited = [0 for i in range(n)] # for is visit and distance\n graph = {i:[] for i in range(1, n+1)}\n \n # make graph\n for x, y in edge:\n graph[x].append(y)\n graph[y].append(x)\n \n # bfs\n queue = [1]\n visited[0] = 0\n while len(queue) != 0:\n c = queue.pop(0)\n for v in graph[c]:\n if visited[v-1] == 0 and v != 1:\n queue.append(v)\n visited[v-1] = visited[c-1] + 1\n\n return visited.count(max(visited))\n\n'''\n# retry 21.09.13\ndef solution(n, edge):\n answers = [0] * (n+1)\n visit = [False] * (n+1)\n nodes = {i: [] for i in range(1,n+1)}\n queue = [1]\n for x, y in edge:\n nodes[x].append(y)\n nodes[y].append(x)\n\n while 0 < len(queue):\n front = queue.pop(0)\n visit[front] = True\n for v in nodes[front]:\n if visit[v] == False and v not in queue:\n queue.append(v)\n answers[v] = answers[front] + 1\n max_value = max(answers)\n return answers.count(max_value)\n'''\n","repo_name":"jihye1996/Algorithm","sub_path":"programmers/가장 먼 노드.py","file_name":"가장 먼 노드.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5348265638","text":"import graphene\nfrom graphene_sqlalchemy import SQLAlchemyObjectType\nfrom sqlalchemy import func\n\nfrom .models import Product as ProductModel\nfrom utilities.utility import update_entity_fields\n\nclass Product(SQLAlchemyObjectType):\n class Meta:\n model = ProductModel\n\nclass Query(graphene.ObjectType):\n all_products = graphene.List(\n Product,\n description=\"Query That returns a list of all products\")\n\n def resolve_all_products(self, info):\n \"\"\"\n Returns list of all products\n \"\"\"\n query = Product.get_query(info)\n return query.order_by(func.lower(ProductModel.name)).all()\n\nclass CreateProduct(graphene.Mutation):\n \"\"\"\n Returns the product payload after creating\n \"\"\"\n class Arguments:\n name = graphene.String(required=True)\n price = graphene.Int(required=True)\n category = graphene.String(required=True)\n product = graphene.Field(Product)\n\n def mutate(self, info, **kwargs):\n product = ProductModel(**kwargs)\n product.save()\n return CreateProduct(product=product)\n\nclass UpdateProduct(graphene.Mutation):\n\n class Arguments:\n name = graphene.String()\n price = graphene.Int()\n category = graphene.String()\n product_id = graphene.Int()\n product = graphene.Field(Product)\n\n def mutate(self, info, product_id, **kwargs):\n product = Product.get_query(info)\n product_obj = product.filter(\n ProductModel.id == product_id\n ).first()\n if not product:\n raise GraphQLError(\"ProductModel not found\")\n update_entity_fields(product_obj, **kwargs)\n product_obj.save()\n return UpdateProduct(product=product_obj)\n\nclass DeleteProduct(graphene.Mutation):\n \"\"\"\n Returns the product payload after deleting a product\n \"\"\"\n class Arguments:\n product_id = graphene.Int(required=True)\n\n product = graphene.Field(Product)\n\n def mutate(self, info, product_id, **kwargs):\n query = Product.get_query(info)\n product = query.filter(ProductModel.id == product_id).first()\n if not product:\n raise GraphQLError(\"ProductModel not found\")\n product.delete()\n return DeleteProduct(product=product)\n\nclass Mutation(graphene.ObjectType):\n create_product = CreateProduct.Field(\n description=\"Creates a new product with the arguments\")\n update_product = UpdateProduct.Field(\n description=\"Updates existing product\"\n )\n delete_product = DeleteProduct.Field(\n description = \"Delete product\"\n )\n","repo_name":"kwanj-k/flask_sm","sub_path":"api/product/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40119299606","text":"\r\nimport random\r\nimport math\r\nimport os, sys\r\nimport time\r\nimport importlib\r\nimport traceback\r\nfrom collections import defaultdict\r\n\r\nfrom PIL import Image, ImageDraw, ImageFont\r\nfrom pyglet import (graphics, gl)\r\nfrom pyglet.image import ImageData\r\n\r\nimport cocos\r\nfrom cocos.cocosnode import CocosNode\r\nimport cocos.actions as act\r\nimport cocos.euclid as eu\r\nfrom cocos.layer import Layer, ColorLayer\r\nfrom cocos.sprite import Sprite\r\nfrom cocos.text import Label\r\nfrom cocos.director import director\r\n\r\nfrom Box2D import (b2, b2Vec2)\r\n\r\n\r\nclass EventOnce:\r\n '''\r\n Event object that can call multiple observer functions with arbitrary args\r\n EventOnce acts as a trigger, only broadcasts the data once\r\n '''\r\n def __init__(self):\r\n self.__observers = []\r\n\r\n def __iadd__(self, cb):\r\n self.__observers.append(cb)\r\n return self\r\n\r\n def __isub__(self, cb):\r\n self.__observers.remove(cb)\r\n return self\r\n\r\n def __call__(self, *args, **kwargs):\r\n for o in self.__observers:\r\n o(*args, **kwargs)\r\n del self.__observers[:]\r\n\r\n\r\nclass EntityPhysMixin:\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self._body = None\r\n\r\n\r\nclass Entity(EntityPhysMixin, CocosNode):\r\n '''\r\n Game entity that renders as primitives\r\n '''\r\n def draw_lines(self, color):\r\n vert_buf = []\r\n color_buf = []\r\n\r\n for fixture in self._body.fixtures:\r\n verts = [(self._body.transform * v) * Mechanics.PX_PER_METER for v in fixture.shape.vertices]\r\n for v in verts:\r\n vert_buf.extend([v.x, v.y])\r\n color_buf.extend(color)\r\n\r\n graphics.draw(len(vert_buf) // 2, gl.GL_LINES, ('v2f', vert_buf), ('c4B', color_buf))\r\n\r\n def draw_poly(self, color):\r\n for fixture in self._body.fixtures:\r\n verts = [(self._body.transform * v) * Mechanics.PX_PER_METER for v in fixture.shape.vertices]\r\n\r\n vert_buf = []\r\n color_buf = []\r\n for v in verts:\r\n vert_buf.extend([v.x, v.y])\r\n color_buf.extend(color)\r\n\r\n graphics.draw(len(vert_buf) // 2, gl.GL_POLYGON, ('v2f', vert_buf), ('c4B', color_buf))\r\n\r\n\r\nclass SpriteEntity(EntityPhysMixin, Sprite):\r\n '''\r\n Game entity that renders as a sprite circle\r\n '''\r\n def __init__(self, size, color):\r\n super().__init__(self.__create_image(size, color))\r\n self.__size = size\r\n\r\n def __create_image(self, size, color):\r\n im = Image.new('RGBA', (int(size), int(size)), (255, 255, 255, 0))\r\n draw = ImageDraw.Draw(im)\r\n draw.ellipse((1, 1, im.size[0]-1, im.size[1]-1), fill=color)\r\n\r\n return ImageData(*im.size, 'RGBA', im.tobytes(), pitch=-im.size[0]*4)\r\n\r\n def draw(self):\r\n x = self._body.worldCenter.x * Mechanics.PX_PER_METER\r\n y = self._body.worldCenter.y * Mechanics.PX_PER_METER\r\n self.position = (x, y)\r\n\r\n super().draw()\r\n\r\n\r\nclass Hitmap(CocosNode):\r\n def __init__(self, width, height):\r\n super().__init__()\r\n self.__image = Image.new('RGBA', (width, height), (255, 255, 255, 0))\r\n\r\n def draw_hit(self, x, y):\r\n draw = ImageDraw.Draw(self.__image)\r\n y = self.__image.size[1] - y\r\n draw.ellipse((x-2, y-2, x+2, y+2), fill=(255, 0, 255, 255))\r\n\r\n def draw(self):\r\n data = ImageData(\r\n *self.__image.size,\r\n 'RGBA', self.__image.tobytes(),\r\n pitch=-self.__image.size[0]*4\r\n )\r\n data.blit(0, 0)\r\n\r\n\r\nclass LabyrinthBounds(Entity):\r\n def init_phys(self, world):\r\n [x0, y0, x1, y1] = Mechanics.getBounds()\r\n\r\n self._body = world.CreateStaticBody(\r\n position=(0, 0),\r\n shapes=[\r\n # bottom, top\r\n b2.edgeShape(vertices=[(x0, y0), (x1, y0)]),\r\n b2.edgeShape(vertices=[(x0, y1), (x1, y1)]),\r\n\r\n # left, right\r\n b2.edgeShape(vertices=[(x0, y0), (x0, y1)]),\r\n b2.edgeShape(vertices=[(x1, y0), (x1, y1)]),\r\n ],\r\n userData=Mechanics.WALL_TAG\r\n )\r\n\r\n def draw(self):\r\n self.draw_lines([0, 0, 0, 255])\r\n\r\n\r\nclass Labyrinth(Entity):\r\n def init_phys(self, world):\r\n [x0, y0, x1, y1] = Mechanics.getBounds()\r\n\r\n # simple demo one\r\n self._body = world.CreateStaticBody(\r\n position=(0, 0),\r\n shapes=[\r\n b2.edgeShape(vertices=[(x1/2, y0 + 4), (x1/2, y1)]),\r\n b2.edgeShape(vertices=[(x1/2 + 4, y1/2), (x1, y1/2)])\r\n ],\r\n userData=Mechanics.WALL_TAG\r\n )\r\n\r\n def draw(self):\r\n self.draw_lines([0, 0, 0, 255])\r\n\r\n\r\nclass Bot(SpriteEntity):\r\n __SIZE = 1\r\n\r\n def __init__(self, position):\r\n super().__init__(self.__SIZE * Mechanics.PX_PER_METER * 2, (255, 0, 0, 255))\r\n self.__initial_pos = position\r\n\r\n def init_phys(self, world):\r\n self._body = world.CreateDynamicBody(\r\n position=self.__initial_pos,\r\n userData=Mechanics.ENDGAME_TAG\r\n )\r\n self._body.CreateCircleFixture(radius=self.__SIZE, density=1, friction=0.3)\r\n\r\n\r\nclass LandingZone(Entity):\r\n '''\r\n The target object where the bot needs to arrive\r\n '''\r\n def init_phys(self, world):\r\n [x0, y0, x1, y1] = Mechanics.getBounds()\r\n\r\n self._body = world.CreateStaticBody(\r\n position=(x1 - 2, y1 - 2),\r\n shapes=b2.polygonShape(box=(2, 2)),\r\n userData=Mechanics.ENDGAME_TAG\r\n )\r\n\r\n def draw(self):\r\n self.draw_poly([0, 255, 0, 100])\r\n\r\n\r\nclass RaycastInterceptor(b2.rayCastCallback):\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.__type = None\r\n self.__point = None\r\n\r\n def ReportFixture(self, fixture, point, normal, fraction):\r\n self.__type = fixture.body.userData\r\n self.__point = point\r\n # stop at closest point\r\n return fraction\r\n\r\n @property\r\n def type(self):\r\n return self.__type\r\n\r\n @property\r\n def point(self):\r\n return self.__point\r\n\r\n\r\nclass Mechanics:\r\n '''\r\n Game mechanics object\r\n Deals with physics\r\n '''\r\n PX_PER_METER = 20.0\r\n ENDGAME_TAG = 'endgame'\r\n WALL_TAG = 'wall'\r\n TARGET_TAG = 'target'\r\n\r\n def __init__(self):\r\n # todo: contact listener for end game\r\n self.__world = b2.world(gravity=(0, 0), doSleep=True)\r\n self.__hitmap = None\r\n\r\n self.target_reached = EventOnce()\r\n\r\n def add_entity(self, entity):\r\n # init mechanics for given entity\r\n self.__init_entity(entity)\r\n\r\n def update(self, dt):\r\n self.__world.Step(1.0 / 60, 10, 10)\r\n\r\n # check contacts for endgame\r\n for c in self.__world.contacts:\r\n d1 = c.fixtureA.body.userData\r\n d2 = c.fixtureB.body.userData\r\n if d1 == d2:\r\n self.target_reached()\r\n break\r\n\r\n def raycast(self, src, dst):\r\n ri = RaycastInterceptor()\r\n self.__world.RayCast(ri, src, dst)\r\n\r\n # draw on hitmap\r\n if self.__hitmap is not None:\r\n x = ri.point[0] * Mechanics.PX_PER_METER\r\n y = ri.point[1] * Mechanics.PX_PER_METER\r\n self.__hitmap.draw_hit(x, y)\r\n\r\n # TODO:\r\n # vert_buf = [float(x) for x in [src[0], src[1], ri.point[0], ri.point[1]]]\r\n # color_buf = [255, 0, 0, 0, 0, 255]\r\n # graphics.draw(len(vert_buf) // 2, gl.GL_LINES, ('v2f', vert_buf), ('c3B', color_buf))\r\n dx = ri.point[0] - src[0]\r\n dy = ri.point[1] - src[1]\r\n mag = (dx*dx + dy*dy) ** 0.5\r\n\r\n return ri.type, mag\r\n\r\n def __init_entity(self, entity):\r\n if type(entity) == Hitmap:\r\n # special case, save it for casts\r\n self.__hitmap = entity\r\n return\r\n\r\n entity.init_phys(self.__world)\r\n\r\n @staticmethod\r\n def getBounds():\r\n x0 = 10 / Mechanics.PX_PER_METER\r\n y0 = 10 / Mechanics.PX_PER_METER\r\n x1 = (Main.WIDTH - 10) / Mechanics.PX_PER_METER\r\n y1 = (Main.HEIGHT - 10) / Mechanics.PX_PER_METER\r\n return [x0, y0, x1, y1]\r\n\r\n\r\nclass Main(ColorLayer):\r\n WIDTH = 600\r\n HEIGHT = 600\r\n\r\n def __init__(self):\r\n super(Main, self).__init__(52, 152, 219, 255)\r\n\r\n self.__mechanics = Mechanics()\r\n self.__mechanics.target_reached += self.__on_target_reached\r\n\r\n self.__add_labyrinth()\r\n self.__add_landing()\r\n self.__add_hitmap()\r\n self.__add_bot()\r\n\r\n self.__start_time = time.time()\r\n self.schedule(self.__mechanics.update)\r\n\r\n def __on_target_reached(self):\r\n self.__bot.remove_action(self.__bot.actions[0])\r\n\r\n total = time.time() - self.__start_time\r\n print('total time was {} seconds'.format(total))\r\n\r\n def __add_bot(self):\r\n try:\r\n mod = importlib.import_module('players.{}'.format(sys.argv[1]))\r\n except:\r\n raise RuntimeError('Cannot load AI module. Inner error: ', traceback.format_exc())\r\n\r\n self.__bot = Bot(position=(7, 24))\r\n action = MoveAction(mod.Bot(), self.__mechanics)\r\n self.__bot.do(action)\r\n self.add(self.__bot)\r\n\r\n def __add_hitmap(self):\r\n self.__hitmap = Hitmap(self.WIDTH, self.HEIGHT)\r\n self.add(self.__hitmap, z=1)\r\n\r\n def __add_labyrinth(self):\r\n self.add(LabyrinthBounds())\r\n self.add(Labyrinth())\r\n\r\n def __add_landing(self):\r\n self.add(LandingZone())\r\n\r\n def add(self, obj, *args, **kwargs):\r\n ''' Override add() that adds physical objects as well '''\r\n super(Main, self).add(obj, *args, **kwargs)\r\n self.__mechanics.add_entity(obj)\r\n\r\n\r\nclass MoveAction(act.Move):\r\n def __init__(self, ai, mechanics):\r\n super().__init__()\r\n self.__ai = ai\r\n self.__mechanics = mechanics\r\n\r\n def step(self, dt):\r\n try:\r\n dx, dy = self.__ai.update(self.__raycast)\r\n except Exception as e:\r\n # any exception in user script results in a null movement vector\r\n print('{} threw exception: {}'.format(self.target, traceback.format_exc()))\r\n dx, dy = 0, 0\r\n\r\n # act on the body with the input, linear motion\r\n b = self.target._body\r\n dx -= b.linearVelocity[0]\r\n dy -= b.linearVelocity[1]\r\n b.ApplyLinearImpulse(b2Vec2(dx, dy) * b.mass, b.worldCenter, wake=True)\r\n\r\n def __raycast(self, dx, dy):\r\n px = self.target._body.position.x\r\n py = self.target._body.position.y\r\n\r\n # make a distant point\r\n magi = 1.0 / ((dx*dx + dy*dy) ** 0.5)\r\n x = px + dx * magi * 99\r\n y = py + dy * magi * 99\r\n return self.__mechanics.raycast(src=(px, py), dst=(x, y))\r\n\r\n def __deepcopy__(self, memo):\r\n # the cocos framework does a deepcopy on the action and we need refs, so skip that\r\n return self\r\n\r\n\r\nclass BotAI:\r\n def update(self, cast_laser):\r\n '''\r\n Returns a movement vector\r\n '''\r\n raise NotImplementedError('overwrite this')\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) != 2:\r\n print('Invalid num of args; syntax ')\r\n exit(1)\r\n\r\n director.init(width=Main.WIDTH, height=Main.HEIGHT, autoscale=True, resizable=True)\r\n director.run(cocos.scene.Scene(Main()))\r\n","repo_name":"laurci/grepit11","sub_path":"labyrinth.py","file_name":"labyrinth.py","file_ext":"py","file_size_in_byte":11501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40864908608","text":"import unittest\nfrom collections import Counter\n\"\"\"\nThis challenge was proposed by Juan\n\"\"\"\ndef sortO(s: str) -> str:\n c = Counter(s)\n b = sorted(c.items(), key=lambda kv: kv[1], reverse=True)\n print(b)\n return \"\".join([i[0] for i in b])\n\nclass TestSortO(unittest.TestCase):\n def test_provided(self):\n self.assertEqual('tbjy',sortO('bbbttyjjjtt'))\n\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"andresesfm/coding_challenges","sub_path":"other/test_sort_by_occurrences.py","file_name":"test_sort_by_occurrences.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"18379193047","text":"from pathlib import Path\n\nimport click\nimport librosa\nimport matplotlib.dates as mdates\nimport numpy as np\nimport torch\nfrom librosa.core import hz_to_mel, mel_frequencies\nfrom loguru import logger\nfrom matplotlib import pyplot as plt\n\nfrom fish_diffusion.modules.pitch_extractors import (\n CrepePitchExtractor,\n DioPitchExtractor,\n HarvestPitchExtractor,\n ParselMouthPitchExtractor,\n)\nfrom fish_diffusion.utils.audio import get_mel_from_audio\n\n# Define global variables\nworkspace = Path(\"pitches_editor\")\nif not workspace.exists():\n workspace.mkdir(parents=True)\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nf_min = 40\nf_max = 16000\nn_mels = 128\n\nmin_mel = hz_to_mel(f_min)\nmax_mel = hz_to_mel(f_max)\nf_to_mel = lambda x: (hz_to_mel(x) - min_mel) / (max_mel - min_mel) * n_mels\nmel_freqs = mel_frequencies(n_mels=n_mels, fmin=f_min, fmax=f_max)\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.argument(\"path\")\ndef extract(path):\n audio, sr = librosa.load(\n path,\n sr=44100,\n mono=True,\n )\n audio = torch.from_numpy(audio).unsqueeze(0).to(device)\n\n mel = (\n get_mel_from_audio(audio, sr, f_min=f_min, f_max=f_max, n_mels=n_mels)\n .cpu()\n .numpy()\n )\n logger.info(f\"Got mel spectrogram with shape {mel.shape}\")\n np.save(workspace / \"mel.npy\", mel)\n\n extractors = {\n \"Crepe\": CrepePitchExtractor,\n \"ParselMouth\": ParselMouthPitchExtractor,\n \"Dio\": DioPitchExtractor,\n }\n\n pitches = {}\n\n for name, extractor in extractors.items():\n pitch_extractor = extractor(f0_min=40.0, f0_max=1600, keep_zeros=False)\n f0 = pitch_extractor(audio, sr, pad_to=mel.shape[-1]).cpu().numpy()\n logger.info(f\"Got {name} pitch with shape {f0.shape}\")\n\n np.save(workspace / f\"{name}.npy\", f0)\n pitches[name] = f0.tolist()\n\n pitches[\"final\"] = pitches[\"Crepe\"]\n data = {\n \"mel\": mel.tolist(),\n \"pitches\": pitches,\n }\n\n import json\n\n with open(workspace / \"data.json\", \"w\") as f:\n json.dump(data, f)\n\n\n@cli.command()\ndef plot():\n mel = np.load(workspace / \"mel.npy\")\n\n all_pitches = {\n k.stem: np.load(k)\n for k in workspace.iterdir()\n if k.suffix == \".npy\" and k.stem != \"mel\"\n }\n\n _, axs = plt.subplots(\n len(all_pitches),\n 1,\n figsize=(10, len(all_pitches) * 3),\n sharex=True,\n sharey=True,\n )\n\n for idx, (name, f0) in enumerate(all_pitches.items()):\n f0 = f_to_mel(f0)\n f0[f0 <= 0] = float(\"nan\")\n\n ax = axs[idx]\n ax.set_title(name)\n\n ax.imshow(mel, aspect=\"auto\", origin=\"lower\")\n ax.plot(f0, label=name, color=\"red\")\n ax.set_yticks(np.arange(0, 128, 10))\n ax.set_yticklabels(np.round(mel_freqs[::10]).astype(int))\n ax.set_ylabel(\"Frequency (Hz)\")\n ax.set_xlabel(\"Time\")\n\n ax.legend()\n\n plt.savefig(\"pitch.png\")\n plt.show()\n\n\n@cli.command()\n@click.argument(\"input_name\")\n@click.argument(\"output_name\")\n@click.argument(\"begin\", type=int)\n@click.argument(\"end\", type=int)\ndef apply(input_name, output_name, begin, end):\n input = np.load(workspace / f\"{input_name}.npy\")\n output = np.load(workspace / f\"{output_name}.npy\")\n\n output[begin:end] = input[begin:end]\n\n np.save(workspace / f\"{output_name}.npy\", output)\n logger.info(f\"Applied {input_name} to {output_name}\")\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"fishaudio/fish-diffusion","sub_path":"tools/pitches_editor.py","file_name":"pitches_editor.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","stars":500,"dataset":"github-code","pt":"80"} +{"seq_id":"24460696624","text":"from trytond.model import fields, ModelView, ModelSQL\nfrom trytond.pool import PoolMeta\nfrom trytond.transaction import Transaction\nfrom trytond.pyson import Eval, Not, Bool, And\n\n\n__all__ = ['Timeline', 'Timesheet']\n__metaclass__ = PoolMeta\n\n\nclass Timeline(ModelSQL, ModelView):\n '''Extending Timesheet_lines\n '''\n __name__ = 'timesheet.line'\n billing_type = fields.Selection([\n ('billable', 'Billable'),\n ('non billable', 'Non Billable'),\n ], 'Billing Type', select=True, required=True, states={\n 'readonly': And(Not(Eval('billing_type') == 'billable'),\n Bool(Eval('billing_type'))),\n })\n\n @staticmethod\n def default_billing_type():\n '''Takes default selected value in timesheet\n '''\n return Transaction().context.get('billable')\n\n\nclass Timesheet(ModelSQL, ModelView):\n '''This class includes marking time on timesheets\n '''\n __name__ = 'project.work'\n timesheet_lines = fields.One2Many(\n 'timesheet.line', 'work', 'Timesheet Lines',\n depends=['timesheet_available', 'active', 'billable'],\n states={\n 'invisible': Not(Bool(Eval('timesheet_available'))),\n 'readonly': Not(Bool(Eval('active'))),\n }, context={'billable': Eval('billable')},\n )\n children = fields.One2Many(\n 'project.work', 'parent', 'Children',\n context={'billable': Eval('billable')}, depends=['billable'],\n )\n\n @staticmethod\n def default_billable():\n '''Takes default selected value in task's timesheet\n '''\n if Transaction().context.get('billable'):\n return Transaction().context.get('billable')\n","repo_name":"simmianand/project_billing","sub_path":"timeline.py","file_name":"timeline.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"37524660286","text":"from flask import Flask, render_template, jsonify, redirect\n# from flask import Flask, render_template\nfrom flask_pymongo import PyMongo\n# from pymongo import MongoClient\nimport os\nimport scrape_mars\n\napp = Flask(__name__)\n\n\n# mongo = PyMongo(app, uri=\"mongodb://localhost:27017/weather_app\")\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_app\")\n# db = mongo.mars\n# mars = db.mars\n#mars = mongo.db.mars\n\n@app.route(\"/\")\ndef index():\n # print(\"getting mars data from mongodb\")\n mars = mongo.db.mars.find_one()\n return render_template(\"index.html\", mars=mars)\n\n\n@app.route(\"/scrape\")\ndef scrape():\n mars = mongo.db.mars\n mars_data = scrape_mars.scrape()\n mars.update({}, mars_data, upsert=True)\n return redirect(\"/\", code=302)\n # print(\"after scrape; ready to redirect\")\n #return redirect(\"https://mars-mission.herokuapp.com\", code=302)\n # return redirect(\"http://localhost:5000/\", code=302)\n # return \"scraping successful\"\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"Samwimb/mission-to-mars","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"34292886035","text":"\"\"\"Problem statement\nhttps://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/bit-manipulation/basics-of-bit-official/ojquestion\n\"\"\"\n\n\ndef toggle_bit(n, i):\n toggle_mask = (1 << i)\n return (n ^ toggle_mask)\n\n\ndef unset_bit(n, i):\n off_mask = ~(1 << i)\n return (n & off_mask)\n\n\ndef set_bit(n, i):\n on_mask = (1 << i)\n return (n | on_mask)\n\n\ndef on_or_off(n, i):\n check_mask = (1 << i)\n return False if (n & check_mask) == 0 else True\n\n\nif __name__ == \"__main__\":\n n = 57\n i = 3\n j = 3\n k = 3\n m = 3\n print(set_bit(n, i))\n print(unset_bit(n, j))\n print(toggle_bit(n, k))\n print(on_or_off(n, m))\n","repo_name":"samyakjain101/DSA","sub_path":"bit_manupulation/q000_basics_of_bit_manupulation.py","file_name":"q000_basics_of_bit_manupulation.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"39698223146","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom Functions import pxf3, kxf, pxminf\nfrom scipy import optimize\n\n# species\nspecies = 'Aru'\nspecies_dict = {'Aru':['Aru_29', 31, 48], 'Bpa':['Bpa_38', 56, 144], 'Pgr':['Pgr_22', 61, 122], 'Pst':['Pst_19', 63, 142], 'Qru':['Qru_42', 51, 88]}\nspecies_code, Vcmax, Jmax = species_dict.get(species)\n\n# read csv\ndf = pd.read_csv('../Data/UMB_daily_average_Gil_2015.csv')\n\n# extract data\ndf = df[['T', 'I', 'D', 'ps15', 'ps30', 'day_len', species_code]]\ndf = df.dropna()\n#df = df.drop(df.index[list(range(76, 83))])\nT = df['T']\nI = df['I']\nD = df['D']\nps = df[['ps15', 'ps30']].mean(1)\nday_length = df['day_len']\nvn_max = df[species_code].max()\nvn = df[species_code]/vn_max\n\ndef muf(c, p50, kxmax, g1,\n ca=400, Kc=460, q=0.3, R=8.314, Jmax=Jmax, Vcmax=Vcmax, z1=0.9, z2=0.9999, a=1.6, L=3.9):\n sapflow_modeled = []\n for i in range(len(vn)):\n # Environmental conditions\n Ti, Ii, Di, psi, dli = T.iloc[i], I.iloc[i], D.iloc[i], ps.iloc[i], day_length.iloc[i]\n # px\n pxmin = pxminf(psi, p50)\n if pxmin < psi:\n pxmax = optimize.minimize_scalar(pxf3, bounds=(pxmin, psi), method='bounded', args=(Ti, Ii, Di, psi, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L))\n px1 = pxf3(pxmin, Ti, Ii, Di, psi, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L)\n px2 = pxf3(pxmax.x, Ti, Ii, Di, psi, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L)\n if px1*px2 < 0:\n px = optimize.brentq(pxf3, pxmin, pxmax.x, args=(Ti, Ii, Di, psi, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L))\n sapflow_modeled.append(kxf(px, kxmax, p50)*(psi-px)*30*60*dli*18/1000000/vn_max)\n else:\n print(i, ' ', c, ' ', p50, ' ', Ti)\n if abs(px1) < abs(px2):\n sapflow_modeled.append(1)\n else:\n sapflow_modeled.append(0)\n else:\n print('pxmin > ps')\n sapflow_modeled.append(100)\n return sapflow_modeled\n\n# simulation\nc = 10\np50 = -2.974111\nkxmax = 1.852892/10\ng1 = 12.756095/10\nvn_model = muf(c, p50, kxmax, g1)\n\n# figure\nplt.plot(vn, label='Aru_29')\nplt.plot(vn_model, label='model')\nplt.legend()","repo_name":"YaojieLu/Plant_traits_inversion","sub_path":"UMB/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"14492511579","text":"\"\"\"A file interface to nodes for PyTables databases.\n\nThe FileNode module provides a file interface for using inside of\nPyTables database files. Use the new_node() function to create a brand\nnew file node which can be read and written as any ordinary Python\nfile. Use the open_node() function to open an existing (i.e. created\nwith new_node()) node for read-only or read-write access. Read acces\nis always available. Write access (enabled on new files and files\nopened with mode 'a+') only allows appending data to a file node.\n\nCurrently only binary I/O is supported.\n\nSee :ref:`filenode_usersguide` for instructions on use.\n\n.. versionchanged:: 3.0\n In version 3.0 the module as been completely rewritten to be fully\n compliant with the interfaces defined in the :mod:`io` module.\n\n\"\"\"\n\nimport io\nimport os\nimport re\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\n\nimport tables as tb\n\n\nNodeType = 'file'\n\"\"\"Value for NODE_TYPE node system attribute.\"\"\"\n\nNodeTypeVersions = [1, 2]\n\"\"\"Supported values for NODE_TYPE_VERSION node system attribute.\"\"\"\n\n\nclass RawPyTablesIO(io.RawIOBase):\n \"\"\"Base class for raw binary I/O on HDF5 files using PyTables.\"\"\"\n\n # A lambda to turn a size into a shape, for each version.\n _size_to_shape = [\n None,\n lambda l: (l, 1),\n lambda l: (l, ),\n ]\n\n def __init__(self, node, mode=None):\n super().__init__()\n\n self._check_node(node)\n self._check_attributes(node)\n\n if mode is None:\n mode = node._v_file.mode\n else:\n self._check_mode(mode)\n self._cross_check_mode(mode, node._v_file.mode)\n\n self._node = node\n self._mode = mode\n self._pos = 0\n self._version = int(node.attrs.NODE_TYPE_VERSION)\n self._vshape = self._size_to_shape[self._version]\n self._vtype = node.atom.dtype.base.type\n\n # read only attribute\n @property\n def mode(self):\n \"\"\"File mode.\"\"\"\n\n return self._mode\n\n # def tell(self) -> int:\n def tell(self):\n \"\"\"Return current stream position.\"\"\"\n\n self._checkClosed()\n return self._pos\n\n # def seek(self, pos: int, whence: int = 0) -> int:\n def seek(self, pos, whence=0):\n \"\"\"Change stream position.\n\n Change the stream position to byte offset offset. offset is\n interpreted relative to the position indicated by whence. Values\n for whence are:\n\n * 0 -- start of stream (the default); offset should be zero or positive\n * 1 -- current stream position; offset may be negative\n * 2 -- end of stream; offset is usually negative\n\n Return the new absolute position.\n\n \"\"\"\n\n self._checkClosed()\n try:\n pos = pos.__index__()\n # except AttributeError as err:\n # raise TypeError(\"an integer is required\") from err\n except AttributeError:\n raise TypeError(\"an integer is required\")\n if whence == 0:\n if pos < 0:\n raise ValueError(f\"negative seek position {pos!r}\")\n self._pos = pos\n elif whence == 1:\n self._pos = max(0, self._pos + pos)\n elif whence == 2:\n self._pos = max(0, self._node.nrows + pos)\n else:\n raise ValueError(\"invalid whence value\")\n return self._pos\n\n # def seekable(self) -> bool:\n def seekable(self):\n \"\"\"Return whether object supports random access.\n\n If False, seek(), tell() and truncate() will raise IOError. This\n method may need to do a test seek().\n\n \"\"\"\n\n return True\n\n # def fileno(self) -> int:\n def fileno(self):\n \"\"\"Returns underlying file descriptor if one exists.\n\n An IOError is raised if the IO object does not use a file\n descriptor.\n\n \"\"\"\n\n self._checkClosed()\n return self._node._v_file.fileno()\n\n # def close(self) -> None:\n def close(self):\n \"\"\"Flush and close the IO object.\n\n This method has no effect if the file is already closed.\n\n \"\"\"\n\n if not self.closed:\n if getattr(self._node, '_v_file', None) is None:\n warnings.warn(\"host PyTables file is already closed!\")\n\n try:\n super().close()\n finally:\n # Release node object to allow closing the file.\n self._node = None\n\n def flush(self):\n \"\"\"Flush write buffers, if applicable.\n\n This is not implemented for read-only and non-blocking streams.\n\n \"\"\"\n\n self._checkClosed()\n self._node.flush()\n\n # def truncate(self, pos: int = None) -> int:\n def truncate(self, pos=None):\n \"\"\"Truncate file to size bytes.\n\n Size defaults to the current IO position as reported by tell().\n Return the new size.\n\n Currently, this method only makes sense to grow the file node,\n since data can not be rewritten nor deleted.\n\n \"\"\"\n\n self._checkClosed()\n self._checkWritable()\n\n if pos is None:\n pos = self._pos\n elif pos < 0:\n raise ValueError(f\"negative truncate position {pos!r}\")\n\n if pos < self._node.nrows:\n raise OSError(\"truncating is only allowed for growing a file\")\n self._append_zeros(pos - self._node.nrows)\n\n return self.seek(pos)\n\n # def readable(self) -> bool:\n def readable(self):\n \"\"\"Return whether object was opened for reading.\n\n If False, read() will raise IOError.\n\n \"\"\"\n\n mode = self._mode\n return 'r' in mode or '+' in mode\n\n # def writable(self) -> bool:\n def writable(self):\n \"\"\"Return whether object was opened for writing.\n\n If False, write() and truncate() will raise IOError.\n\n \"\"\"\n\n mode = self._mode\n return 'w' in mode or 'a' in mode or '+' in mode\n\n # def readinto(self, b: bytearray) -> int:\n def readinto(self, b):\n \"\"\"Read up to len(b) bytes into b.\n\n Returns number of bytes read (0 for EOF), or None if the object\n is set not to block as has no data to read.\n\n \"\"\"\n\n self._checkClosed()\n self._checkReadable()\n\n if self._pos >= self._node.nrows:\n return 0\n\n n = len(b)\n start = self._pos\n stop = self._pos + n\n\n # XXX optimized path\n # if stop <= self._node.nrows and isinstance(b, np.ndarray):\n # self._node.read(start, stop, out=b)\n # self._pos += n\n # return n\n\n if stop > self._node.nrows:\n stop = self._node.nrows\n n = stop - start\n\n # XXX This ought to work with anything that supports the buffer API\n b[:n] = self._node.read(start, stop).tobytes()\n\n self._pos += n\n\n return n\n\n # def readline(self, limit: int = -1) -> bytes:\n def readline(self, limit=-1):\n \"\"\"Read and return a line from the stream.\n\n If limit is specified, at most limit bytes will be read.\n\n The line terminator is always ``\\\\n`` for binary files; for text\n files, the newlines argument to open can be used to select the line\n terminator(s) recognized.\n\n \"\"\"\n\n self._checkClosed()\n self._checkReadable()\n\n chunksize = self._node.chunkshape[0] if self._node.chunkshape else -1\n\n # XXX: check\n lsep = b'\\n'\n lseplen = len(lsep)\n\n # Set the remaining bytes to read to the specified size.\n remsize = limit\n\n partial = []\n finished = False\n\n while not finished:\n # Read a string limited by the remaining number of bytes.\n if limit <= 0:\n ibuff = self.read(chunksize)\n else:\n ibuff = self.read(min(remsize, chunksize))\n ibufflen = len(ibuff)\n remsize -= ibufflen\n\n if ibufflen >= lseplen:\n # Separator fits, look for EOL string.\n eolindex = ibuff.find(lsep)\n elif ibufflen == 0:\n # EOF was immediately reached.\n finished = True\n continue\n else: # ibufflen < lseplen\n # EOF was hit and separator does not fit. ;)\n partial.append(ibuff)\n finished = True\n continue\n\n if eolindex >= 0:\n # Found an EOL. If there are trailing characters,\n # cut the input buffer and seek back;\n # else add the whole input buffer.\n trailing = ibufflen - lseplen - eolindex # Bytes beyond EOL.\n if trailing > 0:\n obuff = ibuff[:-trailing]\n self.seek(-trailing, 1)\n remsize += trailing\n else:\n obuff = ibuff\n finished = True\n elif lseplen > 1 and (limit <= 0 or remsize > 0):\n # Seek back a little since the end of the read string\n # may have fallen in the middle of the line separator.\n obuff = ibuff[:-lseplen + 1]\n self.seek(-lseplen + 1, 1)\n remsize += lseplen - 1\n else: # eolindex<0 and (lseplen<=1 or (limit>0 and remsize<=0))\n # Did not find an EOL, add the whole input buffer.\n obuff = ibuff\n\n # Append (maybe cut) buffer.\n partial.append(obuff)\n\n # If a limit has been specified and the remaining count\n # reaches zero, the reading is finished.\n if limit > 0 and remsize <= 0:\n finished = True\n\n return b''.join(partial)\n\n # def write(self, b: bytes) -> int:\n def write(self, b):\n \"\"\"Write the given buffer to the IO stream.\n\n Returns the number of bytes written, which may be less than\n len(b).\n\n \"\"\"\n\n self._checkClosed()\n self._checkWritable()\n\n if isinstance(b, str):\n raise TypeError(\"can't write str to binary stream\")\n\n n = len(b)\n if n == 0:\n return 0\n\n pos = self._pos\n\n # Is the pointer beyond the real end of data?\n end2off = pos - self._node.nrows\n if end2off > 0:\n # Zero-fill the gap between the end of data and the pointer.\n self._append_zeros(end2off)\n\n # Append data.\n self._node.append(\n np.ndarray(buffer=b, dtype=self._vtype, shape=self._vshape(n)))\n\n self._pos += n\n\n return n\n\n def _checkClosed(self):\n \"\"\"Checks if file node is open.\n\n Checks whether the file node is open or has been closed. In the\n second case, a ValueError is raised. If the host PyTables has\n been closed, ValueError is also raised.\n\n \"\"\"\n\n super()._checkClosed()\n if getattr(self._node, '_v_file', None) is None:\n raise ValueError(\"host PyTables file is already closed!\")\n\n def _check_node(self, node):\n if not isinstance(node, tb.EArray):\n raise TypeError('the \"node\" parameter should be a tables.EArray')\n if not isinstance(node.atom, tb.UInt8Atom):\n raise TypeError('only nodes with atom \"UInt8Atom\" are allowed')\n\n def _check_mode(self, mode):\n if not isinstance(mode, str):\n raise TypeError(\"invalid mode: %r\" % mode)\n\n modes = set(mode)\n if modes - set(\"arwb+tU\") or len(mode) > len(modes):\n raise ValueError(\"invalid mode: %r\" % mode)\n\n reading = \"r\" in modes\n writing = \"w\" in modes\n appending = \"a\" in modes\n # updating = \"+\" in modes\n text = \"t\" in modes\n binary = \"b\" in modes\n\n if \"U\" in modes:\n if writing or appending:\n raise ValueError(\"can't use U and writing mode at once\")\n reading = True\n\n if text and binary:\n raise ValueError(\"can't have text and binary mode at once\")\n\n if reading + writing + appending > 1:\n raise ValueError(\"can't have read/write/append mode at once\")\n\n if not (reading or writing or appending):\n raise ValueError(\"must have exactly one of read/write/append mode\")\n\n def _cross_check_mode(self, mode, h5filemode):\n # XXX: check\n # readable = bool('r' in mode or '+' in mode)\n # h5readable = bool('r' in h5filemode or '+' in h5filemode)\n #\n # if readable and not h5readable:\n # raise ValueError(\"RawPyTablesIO can't be open in read mode if \"\n # \"the underlying hdf5 file is not readable\")\n\n writable = bool('w' in mode or 'a' in mode or '+' in mode)\n h5writable = bool('w' in h5filemode or 'a' in h5filemode or\n '+' in h5filemode)\n\n if writable and not h5writable:\n raise ValueError(\"RawPyTablesIO can't be open in write mode if \"\n \"the underlying hdf5 file is not writable\")\n\n def _check_attributes(self, node):\n \"\"\"Checks file node-specific attributes.\n\n Checks for the presence and validity\n of the system attributes 'NODE_TYPE' and 'NODE_TYPE_VERSION'\n in the specified PyTables node (leaf).\n ValueError is raised if an attribute is missing or incorrect.\n\n \"\"\"\n\n attrs = node.attrs\n ltype = getattr(attrs, 'NODE_TYPE', None)\n ltypever = getattr(attrs, 'NODE_TYPE_VERSION', None)\n\n if ltype != NodeType:\n raise ValueError(f\"invalid type of node object: {ltype}\")\n if ltypever not in NodeTypeVersions:\n raise ValueError(\n f\"unsupported type version of node object: {ltypever}\")\n\n def _append_zeros(self, size):\n \"\"\"_append_zeros(size) -> None. Appends a string of zeros.\n\n Appends a string of 'size' zeros to the array,\n without moving the file pointer.\n\n \"\"\"\n\n # Appending an empty array would raise an error.\n if size == 0:\n return\n\n # XXX This may be redone to avoid a potentially large in-memory array.\n self._node.append(\n np.zeros(dtype=self._vtype, shape=self._vshape(size)))\n\n\nclass FileNodeMixin:\n \"\"\"Mixin class for FileNode objects.\n\n It provides access to the attribute set of the node that becomes\n available via the attrs property. You can add attributes there, but\n try to avoid attribute names in all caps or starting with '_', since\n they may clash with internal attributes.\n\n \"\"\"\n\n # The attribute set property methods.\n def _get_attrs(self):\n \"\"\"Returns the attribute set of the file node.\"\"\"\n\n # sefl._checkClosed()\n return self._node.attrs\n\n def _set_attrs(self, value):\n \"\"\"set_attrs(string) -> None. Raises ValueError.\"\"\"\n\n raise ValueError(\"changing the whole attribute set is not allowed\")\n\n def _del_attrs(self):\n \"\"\"del_attrs() -> None. Raises ValueError.\"\"\"\n\n raise ValueError(\"deleting the whole attribute set is not allowed\")\n\n # The attribute set property.\n attrs = property(\n _get_attrs, _set_attrs, _del_attrs,\n \"A property pointing to the attribute set of the file node.\")\n\n\nclass ROFileNode(FileNodeMixin, RawPyTablesIO):\n \"\"\"Creates a new read-only file node.\n\n Creates a new read-only file node associated with the specified\n PyTables node, providing a standard Python file interface to it.\n The node has to have been created on a previous occasion\n using the new_node() function.\n\n The node used as storage is also made available via the read-only\n attribute node. Please do not tamper with this object if it's\n avoidable, since you may break the operation of the file node object.\n\n The constructor is not intended to be used directly.\n Use the open_node() function in read-only mode ('r') instead.\n\n :Version 1:\n implements the file storage as a UInt8 uni-dimensional EArray.\n :Version 2:\n uses an UInt8 N vector EArray.\n\n .. versionchanged:: 3.0\n The offset attribute is no more available, please use seek/tell\n methods instead.\n\n .. versionchanged:: 3.0\n The line_separator property is no more available.\n The only line separator used for binary I/O is ``\\\\n``.\n\n \"\"\"\n\n def __init__(self, node):\n RawPyTablesIO.__init__(self, node, 'r')\n self._checkReadable()\n\n @property\n def node(self):\n return self._node\n\n\nclass RAFileNode(FileNodeMixin, RawPyTablesIO):\n \"\"\"Creates a new read-write file node.\n\n The first syntax opens the specified PyTables node, while the\n second one creates a new node in the specified PyTables file.\n In the second case, additional named arguments 'where' and 'name'\n must be passed to specify where the file node is to be created.\n Other named arguments such as 'title' and 'filters' may also be\n passed. The special named argument 'expectedsize', indicating an\n estimate of the file size in bytes, may also be passed.\n\n Write access means reading as well as appending data is allowed.\n\n The node used as storage is also made available via the read-only\n attribute node. Please do not tamper with this object if it's\n avoidable, since you may break the operation of the file node object.\n\n The constructor is not intended to be used directly.\n Use the new_node() or open_node() functions instead.\n\n :Version 1:\n implements the file storage as a UInt8 uni-dimensional EArray.\n :Version 2:\n uses an UInt8 N vector EArray.\n\n .. versionchanged:: 3.0\n The offset attribute is no more available, please use seek/tell\n methods instead.\n\n .. versionchanged:: 3.0\n The line_separator property is no more available.\n The only line separator used for binary I/O is ``\\\\n``.\n\n \"\"\"\n\n # The atom representing a byte in the array, for each version.\n _byte_shape = [\n None,\n (0, 1),\n (0,),\n ]\n\n __allowed_init_kwargs = [\n 'where', 'name', 'title', 'filters', 'expectedsize']\n\n def __init__(self, node, h5file, **kwargs):\n if node is not None:\n # Open an existing node and get its version.\n self._check_attributes(node)\n self._version = node.attrs.NODE_TYPE_VERSION\n elif h5file is not None:\n # Check for allowed keyword arguments,\n # to avoid unwanted arguments falling through to array constructor.\n for kwarg in kwargs:\n if kwarg not in self.__allowed_init_kwargs:\n raise TypeError(\n \"%s keyword argument is not allowed\" % repr(kwarg))\n\n # Turn 'expectedsize' into 'expectedrows'.\n if 'expectedsize' in kwargs:\n # These match since one byte is stored per row.\n expectedrows = kwargs['expectedsize']\n kwargs = kwargs.copy()\n del kwargs['expectedsize']\n kwargs['expectedrows'] = expectedrows\n\n # Create a new array in the specified PyTables file.\n self._version = NodeTypeVersions[-1]\n shape = self._byte_shape[self._version]\n node = h5file.create_earray(\n atom=tb.UInt8Atom(), shape=shape, **kwargs)\n\n # Set the node attributes, else remove the array itself.\n try:\n self._set_attributes(node)\n except RuntimeError:\n h5file.remove_node(kwargs['where'], kwargs['name'])\n raise\n\n RawPyTablesIO.__init__(self, node, 'a+')\n self._checkReadable()\n self._checkWritable()\n\n @property\n def node(self):\n return self._node\n\n def _set_attributes(self, node):\n \"\"\"_set_attributes(node) -> None. Adds file node-specific attributes.\n\n Sets the system attributes 'NODE_TYPE' and 'NODE_TYPE_VERSION'\n in the specified PyTables node (leaf).\n\n \"\"\"\n\n attrs = node.attrs\n attrs.NODE_TYPE = NodeType\n attrs.NODE_TYPE_VERSION = NodeTypeVersions[-1]\n\n\ndef new_node(h5file, **kwargs):\n \"\"\"Creates a new file node object in the specified PyTables file object.\n\n Additional named arguments where and name must be passed to specify where\n the file node is to be created. Other named arguments such as title and\n filters may also be passed.\n\n The special named argument expectedsize, indicating an estimate of the\n file size in bytes, may also be passed. It returns the file node object.\n\n \"\"\"\n\n return RAFileNode(None, h5file, **kwargs)\n\n\ndef open_node(node, mode='r'):\n \"\"\"Opens an existing file node.\n\n Returns a file node object from the existing specified PyTables\n node. If mode is not specified or it is 'r', the file can only be\n read, and the pointer is positioned at the beginning of the file. If\n mode is 'a+', the file can be read and appended, and the pointer is\n positioned at the end of the file.\n\n \"\"\"\n\n if mode == 'r':\n return ROFileNode(node)\n elif mode == 'a+':\n return RAFileNode(node, None)\n else:\n raise OSError(f\"invalid mode: {mode}\")\n\n\ndef save_to_filenode(h5file, filename, where, name=None, overwrite=False,\n title=\"\", filters=None):\n \"\"\"Save a file's contents to a filenode inside a PyTables file.\n\n .. versionadded:: 3.2\n\n Parameters\n ----------\n h5file\n The PyTables file to be written to; can be either a string\n giving the file's location or a :class:`File` object. If a file\n with name *h5file* already exists, it will be opened in\n mode ``a``.\n\n filename\n Path of the file which shall be stored within the PyTables file.\n\n where, name\n Location of the filenode where the data shall be stored. If\n *name* is not given, and *where* is either a :class:`Group`\n object or a string ending on ``/``, the leaf name will be set to\n the file name of *filename*. The *name* will be modified to\n adhere to Python's natural naming convention; the original\n filename will be preserved in the filenode's *_filename*\n attribute.\n\n overwrite\n Whether or not a possibly existing filenode of the specified\n name shall be overwritten.\n\n title\n A description for this node (it sets the ``TITLE`` HDF5\n attribute on disk).\n\n filters\n An instance of the :class:`Filters` class that provides\n information about the desired I/O filters to be applied\n during the life of this object.\n\n \"\"\"\n path = Path(filename).resolve()\n\n # sanity checks\n if not os.access(path, os.R_OK):\n raise OSError(f\"The file '{path}' could not be read\")\n if isinstance(h5file, tb.file.File) and h5file.mode == \"r\":\n raise OSError(f\"The file '{h5file.filename}' is opened read-only\")\n\n # guess filenode's name if necessary\n if name is None:\n if isinstance(where, tb.group.Group):\n name = os.path.split(filename)[1]\n if isinstance(where, str):\n if where.endswith(\"/\"):\n name = os.path.split(filename)[1]\n else:\n nodepath = where.split(\"/\")\n where = \"/\" + \"/\".join(nodepath[:-1])\n name = nodepath[-1]\n\n # sanitize name if necessary\n if not tb.path._python_id_re.match(name):\n name = re.sub('(?![a-zA-Z0-9_]).', \"_\",\n re.sub('^(?![a-zA-Z_]).', \"_\", name))\n\n new_h5file = not isinstance(h5file, tb.file.File)\n f = tb.File(h5file, \"a\") if new_h5file else h5file\n\n # check for already existing filenode\n try:\n f.get_node(where=where, name=name)\n if not overwrite:\n if new_h5file:\n f.close()\n raise OSError(\n f\"Specified node already exists in file '{f.filename}'\"\n )\n except tb.NoSuchNodeError:\n pass\n\n # read data from disk\n data = path.read_bytes()\n\n # remove existing filenode if present\n try:\n f.remove_node(where=where, name=name)\n except tb.NoSuchNodeError:\n pass\n\n # write file's contents to filenode\n fnode = new_node(f, where=where, name=name, title=title, filters=filters)\n fnode.write(data)\n fnode.attrs._filename = path.name\n fnode.close()\n\n # cleanup\n if new_h5file:\n f.close()\n\n\ndef read_from_filenode(h5file, filename, where, name=None, overwrite=False,\n create_target=False):\n r\"\"\"Read a filenode from a PyTables file and write its contents to a file.\n\n .. versionadded:: 3.2\n\n Parameters\n ----------\n h5file\n The PyTables file to be read from; can be either a string\n giving the file's location or a :class:`File` object.\n\n filename\n Path of the file where the contents of the filenode shall be\n written to. If *filename* points to a directory or ends with\n ``/`` (``\\`` on Windows), the filename will be set to the\n *_filename* (if present; otherwise the *name*) attribute of the\n read filenode.\n\n where, name\n Location of the filenode where the data shall be read from. If\n no node *name* can be found at *where*, the first node at\n *where* whose *_filename* attribute matches *name* will be read.\n\n overwrite\n Whether or not a possibly existing file of the specified\n *filename* shall be overwritten.\n\n create_target\n Whether or not the folder hierarchy needed to accomodate the\n given target ``filename`` will be created.\n\n \"\"\"\n path = Path(filename).resolve()\n\n new_h5file = not isinstance(h5file, tb.file.File)\n f = tb.File(h5file, \"r\") if new_h5file else h5file\n try:\n fnode = open_node(f.get_node(where=where, name=name))\n except tb.NoSuchNodeError:\n fnode = None\n for n in f.walk_nodes(where=where, classname=\"EArray\"):\n if n.attrs._filename == name:\n fnode = open_node(n)\n break\n if fnode is None:\n f.close()\n raise tb.NoSuchNodeError(\"A filenode '%s' cannot be found at \"\n \"'%s'\" % (name, where))\n\n # guess output filename if necessary\n # TODO: pathlib.Path strips trailing slash automatically :-(\n if path.is_dir() or filename.endswith(os.path.sep):\n try:\n path = path / fnode.node.attrs._filename\n except Exception:\n path = path / fnode.node.name\n\n if os.access(path, os.R_OK) and not overwrite:\n if new_h5file:\n f.close()\n raise OSError(f\"The file '{path}' already exists\")\n\n # create folder hierarchy if necessary\n if create_target:\n path.parent.mkdir(parents=True, exist_ok=True)\n\n if not os.access(path.parent, os.W_OK):\n if new_h5file:\n f.close()\n raise OSError(\"The file '%s' cannot be written to\" % filename)\n\n # read data from filenode\n data = fnode.read()\n fnode.close()\n\n # store data to file\n path.write_bytes(data)\n\n # cleanup\n del data\n if new_h5file:\n f.close()\n","repo_name":"PyTables/PyTables","sub_path":"tables/nodes/filenode.py","file_name":"filenode.py","file_ext":"py","file_size_in_byte":27127,"program_lang":"python","lang":"en","doc_type":"code","stars":1236,"dataset":"github-code","pt":"80"} +{"seq_id":"33767096132","text":"#! /usr/bin/python\n\nimport sys\nimport json\nimport argparse\n\ndef main():\n\n # set up argument parser\n parser = argparse.ArgumentParser(description=\"Format a single-line JSON file into a more human-readable format.\")\n parser.add_argument(\"file\", help=\"the file to format\")\n\n # parse arguments\n args = parser.parse_args()\n\n # retrieve arguments\n data_file_name = args.file\n\n # process the file\n with open(data_file_name, \"r+\") as json_file:\n\n # read and format the data\n unformatted_data = json_file.read()\n data_as_json = json.loads(unformatted_data)\n formatted_data = json.dumps(data_as_json, indent=4, sort_keys=True)\n\n # rewind the file\n json_file.seek(0)\n\n # rewrite it formatted\n json_file.write(formatted_data)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dblotsky/pymtg","sub_path":"bin/format_json.py","file_name":"format_json.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"26559370251","text":"import os, string\nimport PyPDF2\n\nall_text = \"\"\n# create file object variable\n# opening method will be rb\nfor file in os.listdir(\"Data/\"):\n if file.endswith(\".pdf\"):\n pdffileobj = open(f'Data/{file}', 'rb')\n\n # create reader variable that will read the pdffileobj\n pdfreader = PyPDF2.PdfFileReader(pdffileobj)\n\n # This will store the number of pages of this pdf file\n x = pdfreader.numPages\n\n for i in range(5,x-3):\n\n # create a variable that will select the selected number of pages\n pageobj = pdfreader.getPage(i)\n\n # create text variable which will store all text datafrom pdf file\n text = pageobj.extractText()\n\n text = text.encode(\"ascii\",\"ignore\")\n text = text.decode()\n\n all_text = all_text + \"\\n\" + text\n\n# Write all the text in one txt file\nwith open(\"./Data/all_text.txt\", \"w\") as f:\n f.writelines(all_text)","repo_name":"KeremAydin98/how-would-have-carl-sagan-tweeted","sub_path":"pdf2txt.py","file_name":"pdf2txt.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"74864912898","text":"# https://adventofcode.com/2018/day/2\n\nfrom collections import Counter\n\nfrom src.util.types import Data, Solution\n\n\ndef prepare_data(data: str) -> list[str]:\n return data.splitlines()\n\n\ndef part_1(data):\n sum_2 = 0\n sum_3 = 0\n for id_ in data:\n counter = Counter(id_)\n sum_2 += 2 in counter.values()\n sum_3 += 3 in counter.values()\n return sum_2 * sum_3\n\n\ndef find_ids_differing_by_1(data):\n for id_1 in data:\n for id_2 in data:\n count_differences = 0\n for a, b in zip(id_1, id_2):\n count_differences += a != b\n if count_differences == 1:\n return id_1, id_2\n\n\ndef part_2(data):\n id_1, id_2 = find_ids_differing_by_1(data)\n for x in enumerate(zip(id_1, id_2)):\n i = x[0]\n a, b = x[1]\n if a != b:\n return id_1[:i] + id_1[i+1:]\n\n\ndef solve(data: Data) -> Solution:\n challenge_data = prepare_data(data.input)\n return Solution(\n part_1=part_1(challenge_data),\n part_2=part_2(challenge_data)\n )\n","repo_name":"Farbfetzen/Advent_of_Code","sub_path":"src/year2018/day02.py","file_name":"day02.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"80"} +{"seq_id":"32200413042","text":"questions = {\n \"Who created Python?: \": \"A\",\n \"What year was Python created?: \": \"B\",\n \"Python is tributed to which comedy group?: \": \"C\",\n \"Is the Earth round?: \": \"A\",\n}\n\noptions = [\n [\"A. Guido van Rossum\", \"B. Elon Mush\", \"C. Bill Gates\", \"D. Mark Zuckerberg\"],\n [\"A. 1989\", \"B. 1991\", \"C. 2000\", \"D. 2016\"],\n [\"A. Lonely Island\", \"B. Smoosh\", \"C. Monty Python\", \"D. SNL\"],\n [\"A. True\", \"B. False\", \"C. Sometimes\", \"D. What's Earth\"],\n]\n\n\ndef new_game():\n guesses = []\n correct_guesses = 0\n question_num = 1\n\n for question in questions:\n print(\"---------------\")\n print(question)\n for option in options[question_num - 1]:\n print(option)\n\n guess = input(\"Enter (A, B, C, or D): \").upper()\n guesses.append(guess)\n correct_guesses += check_answer(questions.get(question), guess)\n question_num += 1\n\n display_score(correct_guesses, guess)\n\n\ndef check_answer(answer, guess):\n if answer == guess:\n print(\"CORRECT!\")\n return 1\n else:\n print(\"WRONG!\")\n return 0\n\n\ndef display_score(correct_guesses, guesses):\n print(\"---------------\")\n print(\"RESULTS\")\n print(\"---------------\")\n print(\"Answers: \", end=\"\")\n for question in questions:\n print(questions.get(question), end=\"\")\n print()\n\n print(\"Guesses: \", end=\" \")\n for guess in guesses:\n print(guess, end=\" \")\n print()\n\n score = int((correct_guesses / len(questions)) * 100)\n print(\"Your score is: \" + str(score) + \"%\")\n\n\ndef play_again():\n response = input(\"Do you want to play again? (yes or no): \").upper()\n return response == \"TRUE\"\n\n\nwhile play_again():\n new_game()\n","repo_name":"rvbenlg/python-tutorial","sub_path":"01-bro-code/18-quiz-game.py","file_name":"18-quiz-game.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"14259767397","text":"from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\nfrom django.shortcuts import render, get_object_or_404, redirect\r\nfrom django.template.loader import render_to_string\r\nfrom django.http.response import HttpResponse\r\nfrom django.contrib import messages\r\nfrom .forms import CourseCreate\r\nfrom django.urls import reverse\r\nfrom django.http import Http404\r\nfrom django.views import View\r\nfrom .models import Course, Module, Content, CourseUserRelations\r\nfrom exams.models import Exam, ExamUserRelations\r\nimport json, re\r\n\r\nimport base64\r\nimport io\r\nimport sys\r\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\r\nfrom mimetypes import guess_extension\r\n\r\n\r\nclass CoursesViewFunctions(object):\r\n courses = {}\r\n course_data = {}\r\n\r\n def get_courses(self):\r\n course = Course.objects.all()\r\n len(course)\r\n if len(course) == 0:\r\n return {\"empty\": True}\r\n\r\n paginator = Paginator(course, 6)\r\n page = self.request.GET.get(\"page\")\r\n\r\n try:\r\n self.courses[\"courses_instances\"] = paginator.get_page(page)\r\n except PageNotAnInteger:\r\n self.courses[\"courses_instances\"] = paginator.get_page(1)\r\n except EmptyPage:\r\n self.courses[\"courses_instances\"] = paginator.get_page(paginator.num_pages)\r\n\r\n return self.courses\r\n\r\n def get_owner_courses_exams(self):\r\n user = {\"CoursesEmpty\": False, \"ExamsEmpty\": False}\r\n if self.request.user.is_admin:\r\n course = Course.objects.all()\r\n exam = Exam.objects.all()\r\n else:\r\n course = Course.objects.filter(user=self.request.user)\r\n exam = Exam.objects.filter(user=self.request.user)\r\n\r\n if len(course) == 0:\r\n user[\"CoursesEmpty\"] = True\r\n else:\r\n course_paginator = Paginator(course, 3)\r\n course_page = self.request.GET.get(\"coursepage\")\r\n\r\n try:\r\n user[\"Courses\"] = course_paginator.get_page(course_page)\r\n except PageNotAnInteger:\r\n user[\"Courses\"] = course_paginator.get_page(1)\r\n except EmptyPage:\r\n user[\"Courses\"] = course_paginator.get_page(course_paginator.num_pages)\r\n\r\n if len(exam) == 0:\r\n user[\"ExamsEmpty\"] = True\r\n else:\r\n exam_paginator = Paginator(exam, 3)\r\n exam_page = self.request.GET.get(\"exampage\")\r\n\r\n try:\r\n user[\"Exams\"] = exam_paginator.get_page(exam_page)\r\n except PageNotAnInteger:\r\n user[\"Exams\"] = exam_paginator.get_page(1)\r\n except EmptyPage:\r\n user[\"Exams\"] = exam_paginator.get_page(exam_paginator.num_pages)\r\n\r\n return user\r\n\r\n def get_course_instance(self):\r\n id = self.kwargs.get(\"id\")\r\n course = None\r\n if id is not None:\r\n course = get_object_or_404(Course, id=id)\r\n return course\r\n\r\n def get_module_instance(self):\r\n id = self.kwargs.get(\"idModule\")\r\n module = None\r\n if id is not None:\r\n module = get_object_or_404(Module, id=id)\r\n return module\r\n\r\n def get_content_instance(self):\r\n id = self.kwargs.get(\"idContent\")\r\n content = None\r\n relation = None\r\n if id is not None:\r\n content = get_object_or_404(Content, id=id)\r\n if type(content).__name__ == \"Content\":\r\n if content.content_type == \"5\":\r\n try:\r\n relation = ExamUserRelations.objects.get(\r\n user=self.request.user, exam=content.exam\r\n )\r\n except ExamUserRelations.DoesNotExist:\r\n relation = None\r\n return {\"content\": content, \"relation\": relation}\r\n return content\r\n\r\n def get_course_user_relation(self):\r\n user = {\"courses_empty\": False}\r\n course = CourseUserRelations.objects.filter(user=self.request.user)\r\n\r\n if len(course) == 0:\r\n user[\"courses_empty\"] = True\r\n else:\r\n course_paginator = Paginator(course, 3)\r\n course_page = self.request.GET.get(\"coursepage\")\r\n\r\n try:\r\n user[\"courses_relations\"] = course_paginator.get_page(course_page)\r\n except PageNotAnInteger:\r\n user[\"courses_relations\"] = course_paginator.get_page(1)\r\n except EmptyPage:\r\n user[\"courses_relations\"] = course_paginator.get_page(\r\n course_paginator.num_pages\r\n )\r\n\r\n return user\r\n\r\n def relation_exist(self):\r\n id = self.kwargs.get(\"id\")\r\n if id is None:\r\n return None\r\n\r\n try:\r\n course_instance = Course.objects.get(id=id)\r\n except Course.DoesNotExist:\r\n return None\r\n\r\n try:\r\n relation = CourseUserRelations.objects.get(\r\n user=self.request.user, course=course_instance\r\n )\r\n return True\r\n except CourseUserRelations.DoesNotExist:\r\n return False\r\n\r\n def to_file(self, image, picture_name):\r\n \"\"\"base64 encoded file to Django InMemoryUploadedFile that can be placed into request.FILES.\"\"\"\r\n # 'data:image/png;base64,'\r\n try:\r\n idx = image[:50].find(\",\")\r\n\r\n if not idx or not image.startswith(\"data:image/\"):\r\n raise Exception()\r\n\r\n base64file = image[idx + 1 :]\r\n attributes = image[:idx]\r\n content_type = attributes[len(\"data:\") : attributes.find(\";\")]\r\n except Exception as e:\r\n return None\r\n\r\n f = io.BytesIO(base64.b64decode(base64file))\r\n image = InMemoryUploadedFile(\r\n f,\r\n field_name=\"banner\",\r\n name=picture_name + guess_extension(content_type),\r\n content_type=content_type,\r\n size=sys.getsizeof(f),\r\n charset=None,\r\n )\r\n return image\r\n\r\n\r\nclass CourseCreateView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseCreateView.html\"\r\n\r\n def get(self, request, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n return redirect(\"pages:login-page\")\r\n if not request.user.has_permissions:\r\n messages.error(\r\n request, \"You do not have sufficient permissions to use this feature\"\r\n )\r\n return redirect(\"pages:home-page\")\r\n return render(\r\n request,\r\n self.template_name,\r\n {\r\n \"course_form\": CourseCreate(),\r\n \"exams_instances\": Exam.objects.filter(content=None, user=request.user),\r\n },\r\n )\r\n\r\n def post(self, request, *args, **kwargs):\r\n if not request.user.has_permissions:\r\n messages.error(\r\n request, \"You do not have sufficient permissions to use this feature\"\r\n )\r\n return redirect(\"pages:home-page\")\r\n if request.is_ajax:\r\n course_data = json.loads(self.request.body)[\"Course\"]\r\n banner = self.to_file(\r\n course_data.pop(\"banner\"), course_data[\"name\"] + \"_banner\"\r\n )\r\n course_modules_data = course_data.pop(\"Modules\")\r\n if banner is not None:\r\n request.FILES[\"banner\"] = banner\r\n course = CourseCreate(\r\n course_data, request.FILES, modules=course_modules_data\r\n )\r\n if course.is_valid():\r\n course_instance = course.save(commit=False)\r\n course_instance.user = self.request.user\r\n course_instance.save(modules_list_forms=course.modules_forms())\r\n messages.success(request, \"Course created successfully\")\r\n return HttpResponse(\r\n json.dumps(\r\n {\r\n \"error\": False,\r\n \"url_redirect\": reverse(\"courses:course-owner-list\"),\r\n }\r\n )\r\n )\r\n messages.error(request, \"There is an error in the form.\")\r\n html = (\r\n render_to_string(\r\n self.template_name,\r\n {\r\n \"course_form\": course,\r\n \"exams_instances\": Exam.objects.filter(\r\n content=None, user=request.user\r\n ),\r\n },\r\n request,\r\n )\r\n + \"\"\r\n )\r\n body = re.findall(\"(.*?)\", html, re.DOTALL)\r\n return HttpResponse(json.dumps({\"error\": True, \"content\": body}))\r\n messages.error(request, \"An error has occurred, please try again later.\")\r\n return redirect(\"pages:home-page\")\r\n\r\n\r\nclass CourseListView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseListView.html\"\r\n\r\n def get(self, request, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n return redirect(\"pages:login-page\")\r\n return render(request, self.template_name, self.get_courses())\r\n\r\n\r\nclass CourseMyListView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseMyListView.html\"\r\n\r\n def get(self, request, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n return redirect(\"pages:login-page\")\r\n return render(request, self.template_name, self.get_course_user_relation())\r\n\r\n\r\nclass CourseExamManageView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseExamManageView.html\"\r\n\r\n def get(self, request, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n return redirect(\"pages:login-page\")\r\n if not request.user.has_permissions:\r\n messages.error(\r\n request, \"You do not have sufficient permissions to use this feature\"\r\n )\r\n return redirect(\"pages:home-page\")\r\n return render(request, self.template_name, self.get_owner_courses_exams())\r\n\r\n\r\nclass CourseDetailView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseDetailView.html\"\r\n\r\n def get(self, request, id=None, *args, **kwargs):\r\n course = self.get_course_instance()\r\n if course is not None:\r\n owner = False\r\n registered = False\r\n if request.user.is_authenticated:\r\n owner = True if self.request.user == course.user else False\r\n registered = True if self.relation_exist() else False\r\n return render(\r\n request,\r\n self.template_name,\r\n {\"course_instance\": course, \"Owner\": owner, \"Registered\": registered},\r\n )\r\n messages.error(request, \"that course doesn't exist\")\r\n return redirect(\"courses:course-list\")\r\n\r\n\r\nclass CourseDeleteView(CoursesViewFunctions, View):\r\n def get(self, request, id=None, *args, **kwargs):\r\n return redirect(\"pages:home-page\")\r\n\r\n def post(self, request, *args, **kwargs):\r\n if not request.user.has_permissions:\r\n messages.error(\r\n request, \"You do not have sufficient permissions to use this feature\"\r\n )\r\n return redirect(\"pages:home-page\")\r\n course = self.get_course_instance()\r\n if course is not None:\r\n if (course.user == request.user) or request.user.is_admin:\r\n course.delete()\r\n messages.success(request, \"Course delete\")\r\n return redirect(\"courses:course-owner-list\")\r\n return redirect(\"courses:course-list\")\r\n messages.error(request, \"That course doesn't exist\")\r\n return redirect(\"courses:course-owner-list\")\r\n\r\n\r\nclass CourseUpdateView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseUpdateView.html\"\r\n\r\n def get(self, request, id=None, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n return redirect(\"pages:login-page\")\r\n if not request.user.has_permissions:\r\n messages.error(\r\n request, \"You do not have sufficient permissions to use this feature\"\r\n )\r\n return redirect(\"pages:home-page\")\r\n course = self.get_course_instance()\r\n if course is not None:\r\n return render(\r\n request,\r\n self.template_name,\r\n {\r\n \"course_instance\": course,\r\n \"course_form\": CourseCreate(),\r\n \"exams_instances\": Exam.objects.filter(\r\n content=None, user=course.user\r\n ),\r\n },\r\n )\r\n messages.error(request, \"That course doesn't exist\")\r\n return redirect(\"courses:course-list\")\r\n\r\n def post(self, request, *args, **kwargs):\r\n if not request.user.has_permissions:\r\n messages.error(\r\n request, \"You do not have sufficient permissions to use this feature\"\r\n )\r\n return redirect(\"pages:home-page\")\r\n if request.is_ajax:\r\n courseObject = self.get_course_instance()\r\n if courseObject is not None:\r\n course_data = json.loads(self.request.body)[\"Course\"]\r\n banner = self.to_file(\r\n course_data.pop(\"banner\"), course_data[\"name\"] + \"_banner\"\r\n )\r\n course_modules_data = course_data.pop(\"Modules\")\r\n if banner is not None:\r\n request.FILES[\"banner\"] = banner\r\n course = CourseCreate(\r\n course_data,\r\n request.FILES,\r\n modules=course_modules_data,\r\n instance=self.get_course_instance(),\r\n )\r\n if course.is_valid():\r\n course_instance = course.save(commit=False)\r\n course_instance.save(\r\n module_list=course.modules_forms(), update=True\r\n )\r\n messages.success(\r\n request, \"The course has been successfully edited.\"\r\n )\r\n return HttpResponse(\r\n json.dumps(\r\n {\r\n \"error\": False,\r\n \"url_redirect\": reverse(\"courses:course-owner-list\"),\r\n }\r\n )\r\n )\r\n messages.error(request, \"There is an error in the form.\")\r\n html = (\r\n render_to_string(\r\n self.template_name,\r\n {\r\n \"course_instance\": courseObject,\r\n \"course_form\": course,\r\n \"exams_instances\": Exam.objects.filter(\r\n content=None, user=self.get_course_instance().user\r\n ),\r\n },\r\n request,\r\n )\r\n + \"\"\r\n )\r\n body = re.findall(\"(.*?)\", html, re.DOTALL)\r\n return HttpResponse(json.dumps({\"error\": True, \"content\": body}))\r\n messages.error(request, \"that course doesn't exist\")\r\n return redirect(\"courses:course-list\")\r\n messages.error(request, \"An error has occurred, please try again later\")\r\n return redirect(\"pages:home-page\")\r\n\r\n\r\nclass CourseEnrollView(CoursesViewFunctions, View):\r\n def get(self, request, id=None, *args, **kwargs):\r\n return redirect(\"pages:home-page\")\r\n\r\n def post(self, request, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n messages.warning(request, \"you need to login to register for a course\")\r\n return redirect(\"pages:login-page\")\r\n relation = self.relation_exist()\r\n course = self.get_course_instance()\r\n if relation:\r\n messages.success(request, \"You are already enrolled in this course.\")\r\n return redirect(course.get_detail_url())\r\n elif not relation:\r\n CourseUserRelations.objects.create(user=self.request.user, course=course)\r\n messages.success(request, \"You have successfully enrolled in the course.\")\r\n return redirect(course.get_detail_url())\r\n messages.error(request, \"An error has occurred, please try again later.\")\r\n return redirect(\"courses:course-list\")\r\n\r\n\r\nclass CourseHomeView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseHomeView.html\"\r\n\r\n def get(self, request, id, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n messages.warning(request, \"you need to login to register for a course.\")\r\n return redirect(\"pages:login-page\")\r\n registered = True if self.relation_exist() else False\r\n course = self.get_course_instance()\r\n if not self.relation_exist():\r\n messages.success(\r\n request, \"You need to register to view the course content.\",\r\n )\r\n return redirect(course.get_detail_url())\r\n module = Module.objects.filter(course=course)[0]\r\n return render(\r\n request,\r\n self.template_name,\r\n {\"course_instance\": course, \"module_instance\": module,},\r\n )\r\n\r\n\r\nclass ModuleHomeView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseHomeView.html\"\r\n\r\n def get(self, request, id, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n messages.warning(request, \"you need to login to register for a course.\")\r\n return redirect(\"pages:login-page\")\r\n registered = True if self.relation_exist() else False\r\n course = self.get_course_instance()\r\n if not self.relation_exist():\r\n messages.success(\r\n request, \"You need to register to view the course content.\",\r\n )\r\n return redirect(course.get_detail_url())\r\n module = self.get_module_instance()\r\n return render(\r\n request,\r\n self.template_name,\r\n {\"course_instance\": course, \"module_instance\": module,},\r\n )\r\n\r\n\r\nclass ContentHomeView(CoursesViewFunctions, View):\r\n template_name = \"courses/courseContentView.html\"\r\n\r\n def get(self, request, id, *args, **kwargs):\r\n if not request.user.is_authenticated:\r\n messages.warning(request, \"you need to login to register for a course.\")\r\n return redirect(\"pages:login-page\")\r\n registered = True if self.relation_exist() else False\r\n course = self.get_course_instance()\r\n if not self.relation_exist():\r\n messages.success(\r\n request, \"You need to register to view the course content.\",\r\n )\r\n return redirect(course.get_detail_url())\r\n module = self.get_module_instance()\r\n content = self.get_content_instance()\r\n if type(content).__name__ != \"dict\":\r\n return render(\r\n request,\r\n self.template_name,\r\n {\r\n \"course_instance\": course,\r\n \"module_instance\": module,\r\n \"content_instance\": content,\r\n },\r\n )\r\n return render(\r\n request,\r\n self.template_name,\r\n {\r\n \"course_instance\": course,\r\n \"module_instance\": module,\r\n \"content_instance\": content[\"content\"],\r\n \"relation\": content[\"relation\"],\r\n },\r\n )\r\n\r\n","repo_name":"GiomarOsorio/another-e-learning-platform","sub_path":"src/courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"24294624193","text":"import argparse\nimport os\nimport sys\n\nimport numpy as np\nimport torch\n\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'\n# os.environ['CUDA_VISIBLE_DEVICES'] = '1,2,3'\n# os.environ['CUDA_VISIBLE_DEVICES'] = '3'\ndef main(args):\n # seed\n if args.seed is not None:\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n # torch.backends.cudnn.deterministic = True\n # torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.benchmark = True\n else:\n torch.backends.cudnn.benchmark = True\n\n # dataset selection\n if args.dataset == 'wildtrack' or args.dataset == 'multiviewx':\n if args.variant == '2D':\n from multiview_detector.x_training.W_M.model_run_2D import model_run\n elif args.variant == '2D_SVP':\n from multiview_detector.x_training.W_M.model_run_2D_SVP import model_run\n elif args.variant == '2D_SVP_3D':\n from multiview_detector.x_training.W_M.model_run_2D_SVP_3D import model_run\n else:\n raise Exception('Wrong variants.')\n elif args.dataset == 'citystreet':\n if args.variant == '2D':\n from multiview_detector.x_training.CityStreet.model_run_2D import model_run\n elif args.variant == '2D_SVP':\n from multiview_detector.x_training.CityStreet.model_run_2D_SVP import model_run\n elif args.variant == '2D_SVP_WS':\n from multiview_detector.x_training.CityStreet.model_run_2D_SVP_WS import model_run\n elif args.variant == '2D_SVP_VCW':\n from multiview_detector.x_training.CityStreet.model_run_2D_SVP_VCW import model_run\n elif args.variant == 'MH_2D_SVP':\n from multiview_detector.x_training.CityStreet.model_run_2D_SVP_Multi_height_MVDet import model_run\n elif args.variant == 'MH_2D_SVP_VCW':\n from multiview_detector.x_training.CityStreet.model_run_2D_SVP_VCW_Multi_height import model_run\n else:\n raise Exception('Wrong variants.')\n elif args.dataset == 'cvcs':\n from multiview_detector.x_training.CVCS.model_run import model_run\n else:\n raise Exception('Input wrong dataset name.')\n args.person_heights = list(map(lambda x: int(x), args.person_heights.split(',')))\n\n model_run(args)\n\n\nif __name__ == '__main__':\n # settings\n parser = argparse.ArgumentParser(description='Multiview detector')\n parser.add_argument('--reID', action='store_true')\n parser.add_argument('--variant', type=str, default='2D_SVP_VCW',\n choices=['default', '2D', '2D_SVP', '2D_3D', '2D_SVP_3D', '2D_SVP_WS', '2D_SVP_VCW',\n 'MH_2D_SVP', 'MH_2D_SVP_VCW'])\n parser.add_argument('--arch', type=str, default='vgg16', choices=['vgg16', 'resnet18'])\n parser.add_argument('-d', '--dataset', type=str, default='citystreet',\n choices=['wildtrack', 'multiviewx', 'citystreet', 'cvcs'])\n\n parser.add_argument('-j', '--num_workers', type=int, default=4)\n parser.add_argument('-b', '--batch_size', type=int, default=1, metavar='N',\n help='input batch size for training (default: 1)')\n\n parser.add_argument('--epochs', type=int, default=200, metavar='N', help='number of epochs to train (default: 10)')\n parser.add_argument('--lr', type=float, default=0.01, metavar='LR', help='learning rate (default: 0.1)')\n parser.add_argument('--lrfac', type=float, default=0.01, help='generating smaller lr')\n parser.add_argument('--lr_decay', '--ld', type=float, default=1e-4)\n parser.add_argument('--lr_scheduler', '--lrs', type=str, default='onecycle', choices=['onecycle', 'lambda', 'step'])\n parser.add_argument('--weight_decay', type=float, default=1e-4)\n parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='SGD momentum (default: 0.5)')\n parser.add_argument('--log_interval', type=int, default=50, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--resume', type=str, default=None)\n parser.add_argument('--visualize', action='store_true')\n parser.add_argument('--seed', type=int, default=1, help='random seed (default: None)')\n parser.add_argument('--test', type=str, default=None)\n\n parser.add_argument('--facofmaxgt', '--fm', type=float, default=1000)\n parser.add_argument('--facofmaxgt_gp', '--fmg', type=float, default=10)\n\n parser.add_argument('--fix_2D', type=float, default=1)\n parser.add_argument('--fix_svp', type=float, default=0)\n parser.add_argument('--fix_weight', type=float, default=0)\n\n parser.add_argument('--map_sigma', '--ms', type=float, default=3)\n parser.add_argument('--img_reduce', '--ir', type=float, default=2)\n parser.add_argument('--world_reduce', '--wr', type=float, default=2)\n\n parser.add_argument('--weight_svp', type=float, default=1)\n parser.add_argument('--weight_2D', type=float, default=1)\n parser.add_argument('--weight_ssv', type=float, default=1)\n\n parser.add_argument('--cls_thres', '--ct', type=float, default=0.4)\n parser.add_argument('--nms_thres', '--nt', type=float, default=10)\n parser.add_argument('--dist_thres', '--dt', type=float, default=20)\n\n # parser.add_argument('--person_heights', '--ph', type=list, default=[0, 600, 1200, 1800])\n parser.add_argument('--person_heights', '--ph', type=str, default='1750')\n parser.add_argument('--multiheight', '--mh', type=str, default='3drom', choices=['shot', '3drom'])\n args = parser.parse_args()\n\n main(args)\n","repo_name":"BruceYounggit/VWCW","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26902463520","text":"import sys\n\nN, K = map(int, input().split())\nx = list(map(int, input().split()))\nans = abs(x[0])\nif N == 1:\n print(abs(x[0]))\n sys.exit()\nfor i in range(N - 1):\n if x[i] < 0 and x[i + 1] >= 0:\n c = i\n break\n elif i == N - 2 and x[0] >= 0:\n for l in range(K - 1):\n ans += (x[i + 1] - x[i])\n print(ans)\n sys.exit()\n elif i == N - 2 and x[0] < 0:\n for l in range(K - 1):\n ans += abs(x[i + 1] - x[i])\n print(ans)\n sys.exit()\nans = abs(x[c])\nfor i in range(c - K + 1, c):\n ans += abs(x[i] - x[i + 1])\nANS = ans\nfor i in range(K - 1):\n ans -= abs(x[c - K + 1 + i] - x[c - K + 2 + i])\n ans += abs(x[c + i] - x[c + i + 1])\n if ANS > ans:\n ANS = ans\nprint(ANS)\n","repo_name":"KY2001/atcoder-all-my-submissions","sub_path":"abc107/arc101_a_1576923328.py","file_name":"arc101_a_1576923328.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"74428262979","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split, cross_val_score, KFold\nfrom sklearn.metrics import make_scorer, recall_score, precision_score\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom imblearn.under_sampling import RandomUnderSampler\n\ndf = pd.read_csv('./Games.csv')\n\ncolumns = ['Total Shots Home', 'Total Shots Away', 'Shots Insidebox Home', 'Shots Insidebox Away', 'Fouls Home', 'Fouls Away']\n\ndef func_aux(column):\n return pd.to_numeric(column.apply(lambda x: 0 if x == '-' else x))\n\ndf[columns] = df[columns].apply(func_aux)\n\ncolumns = ['Odd Home', 'Odd Draw',\t'Odd Away']\n\ndef func_aux(column):\n return pd.to_numeric(column.apply(lambda x: x.replace(',', '.')))\n\ndf[columns] = df[columns].apply(func_aux)\n\ndf['Total Actions'] = df['Total Shots Home'] + df['Total Shots Away'] + df['Shots Insidebox Home'] + df['Shots Insidebox Away'] + df['Fouls Home'] + df['Fouls Away']\n\ndf = df[df['Total Actions'] > 0]\n\ndf = df[df['League'] == 'Liga Profesional Argentina'] # apenas Liga Profesional Argentina\n\ndf.drop(['Game', 'League', 'Winner', 'Total Actions'], axis=1, inplace=True)\n\ndef get_outliers_indexes(column, IQR_CONST):\n Q1 = df[column].quantile(0.25)\n Q3 = df[column].quantile(0.75)\n\n IQR = Q3 - Q1 # diferente de .quantile(0.5)\n\n upper_bound = Q3 + IQR_CONST * IQR\n lower_bound = Q1 - IQR_CONST * IQR\n\n indexes = df[(df[column] < lower_bound) | (df[column] > upper_bound)].index\n\n return indexes\n\nscores = []\n\nfor IQR_CONST in [1, 1.25, 1.5, 1.75, 2]:\n print(IQR_CONST)\n df_new = df.copy()\n\n indexes = []\n\n for column in df_new:\n new_outliers = get_outliers_indexes(column, IQR_CONST)\n\n indexes.extend(new_outliers)\n\n indexes_without_duplicates = list(set(indexes))\n\n df_new.drop(indexes_without_duplicates, inplace=True)\n\n X = df_new.loc[:, df_new.columns != 'Over 0.5 HT']\n Y = df_new['Over 0.5 HT']\n\n X, Y = RandomUnderSampler(random_state=42).fit_resample(X, Y)\n\n x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=42)\n\n for learning_rate in [x * 0.05 for x in range(1, 10, 2)]:\n for subsample in [x * 0.1 for x in range(1, 10, 2)]:\n for n_estimators in [1, 2, 4, 8, 16, 32, 64, 100, 200]:\n for max_depth in range(1, 5, 1):\n\n model = GradientBoostingClassifier(\n learning_rate=learning_rate,\n subsample=subsample,\n n_estimators=n_estimators,\n max_depth=max_depth,\n random_state=42,\n )\n\n kf = KFold(n_splits=5, random_state=42, shuffle=True)\n\n # Accuracy/Precision\n\n accuracy = cross_val_score(model, x_train, y_train, cv=kf, scoring='accuracy', n_jobs=-1)\n\n accuracy_1 = cross_val_score(model, x_train, y_train, cv=kf, scoring='precision', n_jobs=-1)\n\n def accuracy_negative(y_true, y_pred):\n return precision_score(y_true, y_pred, pos_label=0)\n\n accuracy_0 = cross_val_score(model, x_train, y_train, cv=kf, scoring=make_scorer(accuracy_negative), n_jobs=-1)\n \n # Mean\n\n accuracy_mean = accuracy.mean()\n\n accuracy_1_mean = accuracy_1.mean()\n\n accuracy_0_mean = accuracy_0.mean()\n\n # Median\n\n accuracy_median = np.median(accuracy)\n\n accuracy_1_median = np.median(accuracy_1)\n\n accuracy_0_median = np.median(accuracy_0)\n\n # Recall Mean\n\n recall_1_mean = cross_val_score(model, x_train, y_train, cv=kf, scoring='recall', n_jobs=-1).mean()\n\n def recall_negative(y_true, y_pred):\n return recall_score(y_true, y_pred, pos_label=0)\n \n recall_0_mean = cross_val_score(model, x_train, y_train, cv=kf, scoring=make_scorer(recall_negative), n_jobs=-1).mean()\n\n scores.append([\n IQR_CONST,\n learning_rate,\n subsample,\n n_estimators,\n max_depth,\n accuracy_mean,\n accuracy_1_mean,\n accuracy_0_mean,\n accuracy_median,\n accuracy_1_median,\n accuracy_0_median,\n recall_1_mean,\n recall_0_mean,\n ])\n\ncolumns = [\n 'iqr',\n 'learning_rate',\n 'subsample',\n 'n_estimators',\n 'max_depth',\n 'accuracy_mean',\n 'accuracy_1_mean',\n 'accuracy_0_mean',\n 'accuracy_median',\n 'accuracy_1_median',\n 'accuracy_0_median',\n 'recall_1_mean',\n 'recall_0_mean'\n]\n\ndf_scores = pd.DataFrame(scores, columns=columns)\ndf_scores.to_csv('70-30 (Liga Profesional Argentina).csv', index=False)","repo_name":"VladeMelo/over-0.5-ht","sub_path":"Estudo Over_HT/Evaluation.py","file_name":"Evaluation.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"5133229642","text":"\r\n#--- IMPORT DEPENDENCIES -------------------------------+\r\nimport sys\r\nimport streamlit as st\r\n\r\n# setting path\r\nsys.path.append('../prompts')\r\nsys.path.append('../source_reliability_score')\r\nsys.path.append('../utils')\r\n\r\n\r\nfrom source_reliability_score import *\r\nfrom prompts import *\r\nfrom utils import *\r\nfrom streamlit_option_menu import option_menu\r\n\r\n\r\n\r\n# --- TITLE --------------------------------------------+\r\nwith st.columns(3)[1]:\r\n st.image(\"media/smart_with_sebi.jpeg\", width=200)\r\n\r\nst.markdown(\"

    SEBI PORTAL

    \", unsafe_allow_html=True)\r\n\r\nwith st.sidebar:\r\n if \"api_token\" not in st.session_state:\r\n st.error(\"Set the API key first!\")\r\n else:\r\n st.success(\"API Key already set!\")\r\n st.markdown(\"**Select a page above!**\")\r\n\r\n# --- OPTION MENU --------------------------------------+\r\n\r\nchoice = option_menu(\r\n menu_title=None,\r\n options=[\"CLAIM DETECTION\", \"SOURCE RELIABILITY RATING\"],\r\n icons=[\"database-fill-exclamation\", \"person-fill-exclamation\"],\r\n menu_icon=\"cast\",\r\n orientation=\"horizontal\",\r\n styles={\r\n \"container\": {\"padding\": \"0!important\", \"background-color\": \"#fafafa\"},\r\n \"icon\": {\"color\": \"orange\", \"font-size\": \"25px\"}, \r\n \"nav-link\": {\"font-size\": \"20px\", \"text-align\": \"left\", \"margin\":\"0px\", \"--hover-color\": \"#eee\"},\r\n \"nav-link-selected\": {\"background-color\": \"indigo\"},\r\n },\r\n)\r\n\r\nif choice == \"CLAIM DETECTION\":\r\n selected = option_menu(\r\n menu_title=None,\r\n options=[\"TEXT\", \"AUDIO\", \"VIDEO\",\"IMAGE\",\"QnA\"],\r\n icons=[\"card-text\", \"volume-up\", \"camera-reels\", \"image\",\"question-circle\"],\r\n menu_icon=\"cast\",\r\n orientation=\"horizontal\",\r\n styles={\r\n \"container\": {\"padding\": \"0!important\", \"background-color\": \"#fafafa\"},\r\n \"icon\": {\"color\": \"orange\", \"font-size\": \"15px\"}, \r\n \"nav-link\": {\"font-size\": \"15px\", \"text-align\": \"left\", \"margin\":\"0px\", \"--hover-color\": \"#eee\"},\r\n \"nav-link-selected\": {\"background-color\": \"indigo\"},\r\n },\r\n )\r\n\r\n \r\n # Main content based on sebi's employee selected\r\n if selected == \"TEXT\":\r\n\r\n st.write(\"**TEXT BASED CLAIM DETECTION:**\\n\\n\")\r\n prompt = st.text_area(\"User Input\")\r\n source_name = st.text_area(\"Source Name\")\r\n source_type = st.text_area(\"Source Type\")\r\n\r\n if st.button(\"Submit\") and prompt:\r\n response = claim_detection_pipeline(prompt)\r\n add_details_source(source_name,source_type,response)\r\n\r\n financial_points = financial_point_extractor(prompt)\r\n display_sebi_rules(financial_points)\r\n \r\n \r\n\r\n if selected == \"AUDIO\":\r\n st.write(\"**AUDIO BASED CLAIM DETECTION:**\")\r\n audio_file = st.file_uploader(\"Upload an audio file\", type=[\"ogg\", \"mp3\", \"wav\"])\r\n\r\n if audio_file:\r\n st.audio(audio_file, format='audio/ogg', start_time=0)\r\n transcript = transcribe_audio(audio_file)\r\n prompt = st.text_area(\"Transcribed User Input\", value=transcript)\r\n source_name = st.text_area(\"Source Name\")\r\n source_type = st.text_area(\"Source Type\")\r\n if st.button(\"Submit\") and prompt:\r\n response = claim_detection_pipeline(prompt)\r\n add_details_source(source_name,source_type,response)\r\n financial_points = financial_point_extractor(prompt)\r\n display_sebi_rules(financial_points)\r\n\r\n\r\n if selected == \"IMAGE\":\r\n st.write(\"**IMAGE BASED CLAIM DETECTION:**\")\r\n image_file = st.file_uploader(\"Upload an image file\", type=[\"png\", \"jpg\", \"jpeg\"])\r\n\r\n if image_file:\r\n st.image(image_file, caption='Uploaded Image.', use_column_width=True,width=300)\r\n text_from_image = get_text_from_image(image_file)\r\n prompt = st.text_area(\"User input image to text:\", value=text_from_image)\r\n source_name = st.text_area(\"Source Name\")\r\n source_type = st.text_area(\"Source Type\")\r\n\r\n if st.button(\"Submit\") and prompt:\r\n response = claim_detection_pipeline(prompt)\r\n add_details_source(source_name,source_type,response)\r\n financial_points = financial_point_extractor(prompt)\r\n display_sebi_rules(financial_points)\r\n\r\n if selected == \"VIDEO\":\r\n st.write(\"**VIDEO BASED CLAIM DETECTION:**\")\r\n video_file = st.file_uploader(\"Upload a video file\", type=[\"mp4\", \"mov\", \"avi\"])\r\n\r\n if video_file:\r\n st.video(video_file, start_time=0)\r\n #----------------------------------------\r\n transcript = video_to_text(video_file)\r\n #----------------------------------------\r\n prompt = st.text_area(\"Transcribed User Input\", value=transcript)\r\n \r\n source_name = st.text_area(\"Source Name\")\r\n source_type = st.text_area(\"Source Type\")\r\n if st.button(\"Submit\") and prompt:\r\n response = claim_detection_pipeline(prompt)\r\n add_details_source(source_name,source_type,response)\r\n financial_points = financial_point_extractor(prompt)\r\n display_sebi_rules(financial_points)\r\n\r\n if selected == \"QnA\":\r\n st.write(\"**Question - Answering**\")\r\n prompt = st.text_area(\"User Input\")\r\n\r\n if st.button(\"Submit\") and prompt:\r\n question_and_answer(prompt)\r\n \r\nif choice == \"SOURCE RELIABILITY RATING\":\r\n if st.button(\"Click here to get the source reliability rating\"):\r\n display_source_scores()\r\n \r\n","repo_name":"hindesh-akash/temp-misleading","sub_path":"pages/03_sebi.py","file_name":"03_sebi.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"72561880899","text":"import os\nimport cv2\nimport pdb\n#from json2xml import json2xml,readfromjson\ncdir=os.getcwd()\noutdir='images/'\nfor directory in ['data/train','data/test']:\n #pdb.set_trace()\n if not os.path.exists(os.path.join(cdir,directory,outdir)):\n os.mkdir('{}/{}/{}'.format(cdir,directory,outdir))\n for files in os.listdir(os.path.join(cdir,directory,\"img\")):\n bgr = cv2.imread(os.path.join(cdir,directory,\"img\",files))\n lab = cv2.cvtColor(bgr,cv2.COLOR_BGR2LAB)\n lab_planes = cv2.split(lab)\n clahe = cv2.createCLAHE(clipLimit=2.0,tileGridSize=(16,16))\n lab_planes[0]=clahe.apply(lab_planes[0])\n lab = cv2.merge(lab_planes)\n bgr = cv2.cvtColor(lab,cv2.COLOR_LAB2BGR)\n cv2.imwrite(os.path.join(cdir,directory,outdir,files),bgr)\n\n","repo_name":"deafcon01/work","sub_path":"clahe.py","file_name":"clahe.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"34293095855","text":"import pathmagic # noqa\nfrom data_structure.min_heap import MinHeap as PriorityQueue\n\n\nclass Pair:\n def __init__(self, vertex: int, psf: str, cost: int):\n self.vertex = vertex\n self.psf = psf\n self.cost = cost\n\n def __lt__(self, other):\n if self.cost < other.cost:\n return True\n return False\n\n def __gt__(self, other):\n if self.cost > other.cost:\n return True\n return False\n\n def __eq__(self, other):\n if self.cost == other.cost:\n return True\n return False\n\n\nclass Edge:\n def __init__(self, src: int, nbr: int, weight: int):\n self.src = src\n self.nbr = nbr\n self.weight = weight\n\n\nclass Graph:\n def __init__(self, graph_arr: list, vertices: int):\n self.graph = [[] for _ in range(vertices)]\n\n for edge in graph_arr:\n v1, v2, wt = edge\n e1 = Edge(src=v1, nbr=v2, weight=wt)\n e2 = Edge(src=v2, nbr=v1, weight=wt)\n\n self.graph[v1].append(e1)\n self.graph[v2].append(e2)\n\n def dijkstras_algo(self, vertices: int, source: int):\n visited = [False] * len(self.graph)\n\n q = PriorityQueue(vertices)\n q.insert(Pair(vertex=source, psf=f\"{source}\", cost=0))\n\n while q.size:\n removed = q.remove_min()\n\n if visited[removed.vertex]:\n continue\n visited[removed.vertex] = True\n print(f\"{removed.vertex} via {removed.psf} @ {removed.cost}\")\n\n for edge in self.graph[removed.vertex]:\n if not visited[edge.nbr]:\n q.insert(\n Pair(\n vertex=edge.nbr,\n psf=f\"{removed.psf}{edge.nbr}\",\n cost=removed.cost + edge.weight,\n )\n )\n\n\nif __name__ == \"__main__\":\n vertices = 7\n k = 9\n arr = [\n [0, 1, 10],\n [1, 2, 10],\n [2, 3, 10],\n [0, 3, 40],\n [3, 4, 2],\n [4, 5, 3],\n [5, 6, 3],\n [4, 6, 8],\n [2, 5, 5],\n ]\n g = Graph(arr, vertices)\n source = 0\n g.dijkstras_algo(vertices, source)\n","repo_name":"samyakjain101/DSA","sub_path":"graph/q008_dijkstras_algo.py","file_name":"q008_dijkstras_algo.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"29026544013","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nimport math\n\nclass ShipmentPackage(Document):\n\tdef validate(self):\n\t\tif self.uom == 'cm':\n\t\t\tvolume = self.length * self.width * self.height\n\t\t\tif self.volumetric_factor > 0:\n\t\t\t\tvol_wt = volume/self.volumetric_factor\n\t\t\telse:\n\t\t\t\tfrappe.throw(\"Volumetric Factor has to be greater than Zero\")\n\t\t\tfrappe.msgprint(str(vol_wt))\n\t\t\tself.volumetric_weight_in_kgs = self.round_up_to_factor(vol_wt, 0.5) + 0.5\n\n\tdef round_up_to_factor(self, number, factor):\n\t\trounded_number = math.ceil(number/factor) * factor\n\t\treturn rounded_number\n","repo_name":"adityaduggal/rigpl-erpnext","sub_path":"rigpl_erpnext/rigpl_erpnext/doctype/shipment_package/shipment_package.py","file_name":"shipment_package.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"80"} +{"seq_id":"7268971366","text":"import tkinter as tk\nwindow=tk.Tk()\nwindow.geometry('500x300')\nshowText=tk.StringVar()\nlableOne=tk.Label(window,textvariable=showText,width=50,bg='red')\nlableOne.pack()\ndef show(value):\n print(value)\n showText.set(value)\nscaleOne=tk.Scale(window,label='scale',from_=0,to=100,orient=tk.HORIZONTAL,length=600,showvalue=0,tickinterval=1,resolution=1,command=show)\nscaleOne.pack()\nwindow.mainloop()","repo_name":"tianjingle/think","sub_path":"src/tkinterLean/ScaleLearn.py","file_name":"ScaleLearn.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"8876752089","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function, division, absolute_import\n\nimport os\nimport codecs\n\nimport six\n\nfrom .reqs import project_import_modules, is_std_or_local_lib, is_base_module\nfrom .utils import lines_diff\nfrom .log import logger\nfrom .modules import ReqsModules\n\n\nclass GenerateReqs(object):\n _force_modules_reqs = dict()\n\n def __init__(self, save_path, project_path, ignores,\n installed_pkgs, comparison_operator='=='):\n self._save_path = save_path\n self._project_path = project_path\n self._ignores = ignores\n self._installed_pkgs = installed_pkgs\n self._maybe_local_mods = set()\n self._local_mods = dict()\n self._relative_imports = set()\n self._comparison_operator = comparison_operator\n\n def extract_reqs(self, module_callback=None, entry_point_filename=None):\n \"\"\"Extract requirements from project.\"\"\"\n\n def _internal_create_req(_version, _pkg_name, _name, _modules):\n if _name not in _modules:\n _modules.add(_name, _name, 0)\n if not _version and _pkg_name and _pkg_name.startswith('-e '):\n return ('{} @ {}'.format(_name, _pkg_name.replace('-e ', '', 1)), _version, _modules[_name])\n else:\n return (_pkg_name, _version, _modules[_name])\n\n reqs = ReqsModules()\n guess = ReqsModules()\n local = ReqsModules()\n\n num_local_mod = 0\n if self.__module__:\n # create a copy, do not change the class set\n our_module = self.__module__.split('.')[0]\n if our_module and our_module not in self._force_modules_reqs:\n from ...version import __version__\n self._force_modules_reqs[our_module] = __version__\n\n # make the entry point absolute (relative to the root path)\n if entry_point_filename and not os.path.isabs(entry_point_filename):\n entry_point_filename = os.path.join(self._project_path, entry_point_filename) \\\n if os.path.isdir(self._project_path) else None\n\n # check if the entry point script is self contained, i.e. does not use the rest of the project\n if entry_point_filename and os.path.isfile(entry_point_filename) and not self._local_mods:\n modules, try_imports, local_mods = project_import_modules(entry_point_filename, self._ignores)\n if not local_mods:\n # update the self._local_mods\n self._filter_modules(modules, local_mods)\n # check how many local modules we have, excluding ourselves\n num_local_mod = len(set(self._local_mods.keys()) - set(self._force_modules_reqs.keys()))\n\n # if we have any module/package we cannot find, take no chances and scan the entire project\n # if we have local modules and they are not just us.\n if num_local_mod or local_mods or self._relative_imports:\n modules, try_imports, local_mods = project_import_modules(\n self._project_path, self._ignores)\n\n else:\n modules, try_imports, local_mods = project_import_modules(\n self._project_path, self._ignores)\n\n if module_callback:\n modules = module_callback(modules)\n\n # Filtering modules\n candidates = self._filter_modules(modules, local_mods)\n\n # make sure we are in candidates\n candidates |= set(self._force_modules_reqs.keys())\n\n logger.info('Check module in local environment.')\n reqs_module_name = []\n for name in candidates:\n logger.info('Checking module: %s', name)\n if name in self._installed_pkgs:\n pkginfo = self._installed_pkgs[name]\n for pkg, (pkg_name, version) in ({\"\": pkginfo} if not isinstance(pkginfo, dict) else pkginfo).items():\n _name = pkg or name\n reqs.add(*_internal_create_req(version, pkg_name, _name, modules))\n reqs_module_name.append(_name)\n elif name in modules:\n guess.add(name, 0, modules[name])\n\n # add local modules, so we know what is used but not installed.\n project_path = os.path.realpath(self._project_path)\n for name in self._local_mods:\n if name in modules and name not in reqs_module_name:\n if name in self._force_modules_reqs:\n reqs.add(name, self._force_modules_reqs[name], modules[name])\n reqs_module_name.append(name)\n continue\n\n # if this is a base module, we have it in installed modules but package name is None\n mod_path = os.path.realpath(self._local_mods[name])\n if is_base_module(mod_path):\n continue\n\n # if this is a folder of our project, we can safely ignore it\n if (six.PY3 and os.path.commonpath([project_path]) == os.path.commonpath([project_path, mod_path])) or \\\n (six.PY2 and\n os.path.commonprefix([project_path]) == os.path.commonprefix([project_path, mod_path])):\n continue\n\n relpath = os.path.relpath(self._local_mods[name], self._project_path)\n if not relpath.startswith('.'):\n relpath = '.' + os.path.sep + relpath\n local.add(name, relpath, modules[name])\n\n return reqs, try_imports, guess, local\n\n @classmethod\n def get_forced_modules(cls):\n return cls._force_modules_reqs\n\n @classmethod\n def add_forced_module(cls, module_name, module_version):\n cls._force_modules_reqs[module_name] = module_version\n\n def _write_reqs(self, reqs):\n print('Writing requirements to \"{0}\"'.format(\n self._save_path))\n with open(self._save_path, 'w+') as f:\n f.write('# Requirements automatically generated by pigar.\\n'\n '# https://github.com/damnever/pigar\\n')\n for k, v in reqs.sorted_items():\n f.write('\\n')\n f.write(''.join(['# {0}\\n'.format(c)\n for c in v.comments.sorted_items()]))\n if k == '-e':\n f.write('{0} {1}\\n'.format(k, v.version))\n elif v:\n f.write('{0} {1} {2}\\n'.format(\n k, self._comparison_operator, v.version))\n else:\n f.write('{0}\\n'.format(k))\n\n def _best_matchs(self, name, pkgs):\n # If imported name equals to package name.\n if name in pkgs:\n return [pkgs[pkgs.index(name)]]\n # If not, return all possible packages.\n return pkgs\n\n def _filter_modules(self, modules, local_mods):\n candidates = set()\n\n logger.info('Filtering modules ...')\n for module in modules:\n logger.info('Checking module: %s', module)\n if not module:\n continue\n if module.startswith('.'):\n self._relative_imports.add(module)\n continue\n if module in local_mods:\n self._maybe_local_mods.add(module)\n module_std_local = is_std_or_local_lib(module)\n if module_std_local is True:\n continue\n if isinstance(module_std_local, str):\n self._local_mods[module] = module_std_local\n continue\n candidates.add(module)\n\n return candidates\n\n def _invalid_reqs(self, reqs):\n for name, detail in reqs.sorted_items():\n print(\n ' {0} referenced from:\\n {1}'.format(\n name,\n '\\n '.join(detail.comments.sorted_items())\n )\n )\n\n def _save_old_reqs(self):\n if os.path.isfile(self._save_path):\n with codecs.open(self._save_path, 'rb', 'utf-8') as f:\n self._old_reqs = f.readlines()\n\n def _reqs_diff(self):\n if not hasattr(self, '_old_reqs'):\n return\n with codecs.open(self._save_path, 'rb', 'utf-8') as f:\n new_reqs = f.readlines()\n is_diff, diffs = lines_diff(self._old_reqs, new_reqs)\n msg = 'Requirements file has been covered, '\n if is_diff:\n msg += 'there is the difference:'\n print('{0}\\n{1}'.format(msg, ''.join(diffs)), end='')\n else:\n msg += 'no difference.'\n print(msg)\n","repo_name":"allegroai/clearml","sub_path":"clearml/utilities/pigar/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":8556,"program_lang":"python","lang":"en","doc_type":"code","stars":4861,"dataset":"github-code","pt":"80"} +{"seq_id":"20982728473","text":"import numpy as np\n\nfrom common.common_func import *\n# from common.common_cls import *\nfrom environment.envs import *\nfrom environment.envs.pathplanning.samplingmap import samplingmap\n\n\nclass UGV_Bidirectional_Continuous(samplingmap, rl_base):\n def __init__(self, initPhi: float, save_cfg: bool, x_size: float, y_size: float, start: list, terminal: list):\n \"\"\"\n :param initPhi: initial phi\n :param save_cfg: svae to model file or not\n \"\"\"\n super(UGV_Bidirectional_Continuous, self).__init__(width=400,\n height=400,\n x_size=x_size,\n y_size=y_size,\n image_name='TwoWheelUGV',\n start=start,\n terminal=terminal,\n obs=None,\n draw=False)\n '''physical parameters'''\n self.initX = self.start[0]\n self.initY = self.start[1]\n self.initPhi = initPhi\n self.x = self.initX # X\n self.y = self.initY # Y\n self.phi = self.initPhi # 车的转角\n self.dx = 0\n self.dy = 0\n self.dphi = 0\n self.wLeft = 0.\n self.wRight = 0.\n\n self.wMax = 10 # 车轮最大角速度rad/s\n self.r = 0.1 # 车轮半径\n self.l_wheel = 0.06 # 车轮厚度\n self.rBody = 0.15 # 车主体半径\n self.L = 2 * self.rBody # 车主体直径\n self.dt = 0.02 # 50Hz\n self.time = 0. # time\n self.timeMax = 8.0\n self.vMax = 5 # 最大速度 5 m/s\n self.vMin = -5\n self.omegaMax = deg2rad(360) # 最大角速度 2pi\n self.omegaMin = deg2rad(-360)\n\n self.miss = 0.4\n self.name = 'UGVBidirectional'\n '''physical parameters'''\n\n '''rl_base'''\n self.static_gain = 2\n self.state_dim = 8 # ex, ey, x, y, phi, dx, dy, dphi\n self.state_num = [math.inf, math.inf, math.inf, math.inf, math.inf, math.inf, math.inf, math.inf]\n self.state_step = [None, None, None, None, None, None, None, None]\n self.state_space = [None, None, None, None, None, None, None, None]\n self.state_range = [[-self.x_size, self.x_size],\n [-self.y_size, self.y_size],\n [0, self.x_size],\n [0, self.y_size],\n [-math.inf, math.inf],\n [-self.r * self.wMax, self.r * self.wMax],\n [-self.r * self.wMax, self.r * self.wMax],\n [self.r / self.L * 2 * self.r * self.wMax, -self.r / self.L * 2 * self.r * self.wMax]]\n self.isStateContinuous = [True, True, True, True, True, True, True, True]\n self.initial_state = self.state_norm()\n self.current_state = self.initial_state.copy()\n self.next_state = self.initial_state.copy()\n\n self.action_dim = 2\n self.action_step = [None, None]\n self.action_range = [[-self.wMax, self.wMax], [-self.wMax, self.wMax]]\n self.action_num = [math.inf, math.inf]\n self.action_space = [None, None]\n self.isActionContinuous = [True, True]\n self.initial_action = [0.0, 0.0]\n self.current_action = self.initial_action.copy()\n\n self.reward = 0.0\n self.is_terminal = False\n self.terminal_flag = 0 # 0-正常 1-出界 2-超时 3-成功\n '''rl_base'''\n\n '''visualization_opencv'''\n self.show_dynamic_image(isWait=False)\n '''visualization_opencv'''\n\n '''datasave'''\n self.saveX = [self.x]\n self.saveY = [self.y]\n self.savePhi = [self.phi]\n self.savedX = [self.dx]\n self.savedY = [self.dy]\n self.savedPhi = [self.dphi]\n self.savewLeft = [self.wLeft]\n self.savewRight = [self.wRight]\n self.saveTime = [self.time]\n '''datasave'''\n if save_cfg:\n self.saveModel2XML()\n\n def draw_car(self):\n self.image = self.image_temp.copy()\n rBody = self.rBody * 3\n r = self.r * 2\n l_wheel = self.l_wheel * 2\n cv.circle(self.image, self.dis2pixel([self.x, self.y]), self.length2pixel(rBody), Color().Orange, -1) # 主体\n '''两个车轮'''\n # left\n pts_left = [[r, rBody], [r, rBody - l_wheel], [-r, rBody - l_wheel], [-r, rBody]]\n pts_left = points_rotate(pts_left, self.phi)\n pts_left = points_move(pts_left, [self.x, self.y])\n cv.fillConvexPoly(self.image, points=np.array([list(self.dis2pixel(pt)) for pt in pts_left]), color=Color().Red)\n # right\n pts_right = [[r, -rBody], [r, -rBody + l_wheel], [-r, -rBody + l_wheel], [-r, -rBody]]\n pts_right = points_rotate(pts_right, self.phi)\n pts_right = points_move(pts_right, [self.x, self.y])\n cv.fillConvexPoly(self.image, points=np.array([list(self.dis2pixel(pt)) for pt in pts_right]), color=Color().Red)\n '''两个车轮'''\n # 额外画一个圆形,标志头\n head = [r - 0.02, 0]\n head = points_rotate(head, self.phi)\n head = points_move(head, [self.x, self.y])\n cv.circle(self.image, self.dis2pixel(head), self.length2pixel(0.1), Color().Black, -1) # 主体\n\n def draw_terminal(self):\n if self.terminal is not None and self.terminal != []:\n cv.circle(self.image, self.dis2pixel(self.terminal), 5, Color().random_color_by_BGR(), -1)\n\n def draw_region_grid(self, xNUm: int = 3, yNum: int = 3):\n if xNUm <= 1 or yNum <= 1:\n pass\n else:\n xStep = self.x_size / xNUm\n yStep = self.y_size / yNum\n for i in range(yNum - 1):\n pt1 = self.dis2pixel([0, 0 + (i + 1) * yStep])\n pt2 = self.dis2pixel([self.x_size, 0 + (i + 1) * yStep])\n cv.line(self.image, pt1, pt2, Color().Black, 1)\n for i in range(xNUm - 1):\n pt1 = self.dis2pixel([0 + (i + 1) * xStep, 0])\n pt2 = self.dis2pixel([0 + (i + 1) * xStep, self.y_size])\n cv.line(self.image, pt1, pt2, Color().Black, 1)\n\n def show_dynamic_image(self, isWait):\n self.image_temp = self.image.copy()\n self.map_draw_boundary()\n self.draw_car()\n self.draw_terminal()\n self.draw_region_grid(xNUm=3, yNum=3)\n\n cv.putText(self.image, str(round(self.time, 3)), (0, 15), cv.FONT_HERSHEY_COMPLEX, 0.6, Color().Purple, 1)\n cv.imshow(self.name4image, self.image)\n cv.waitKey(0) if isWait else cv.waitKey(1)\n self.save = self.image.copy()\n self.image = self.image_temp.copy()\n\n def state_norm(self):\n # [self.terminal[0] - self.x, self.terminal[1] - self.y, self.x, self.y, self.phi, self.dx, self.dy, self.dphi]\n _ex = (self.terminal[0] - self.x) / self.x_size * self.static_gain\n _ey = (self.terminal[1] - self.y) / self.y_size * self.static_gain\n _x = (2 * self.x / self.x_size - 1) * self.static_gain\n _y = (2 * self.y / self.y_size - 1) * self.static_gain\n _phi = self.phi / np.pi * self.static_gain\n _dx = self.dx / self.vMax * self.static_gain\n _dy = self.dy / self.vMax * self.static_gain\n _dphi = self.dphi / self.omegaMax * self.static_gain\n return np.array([_ex, _ey, _x, _y, _phi, _dx, _dy, _dphi])\n\n def inverse_state_norm(self, s: np.ndarray):\n # [self.terminal[0] - self.x, self.terminal[1] - self.y, self.x, self.y, self.phi, self.dx, self.dy, self.dphi]\n s[0] = s[0] / self.static_gain * self.x_size\n s[1] = s[1] / self.static_gain * self.y_size\n s[2] = (s[2] / self.static_gain + 1) * self.x_size / 2\n s[3] = (s[3] / self.static_gain + 1) * self.y_size / 2\n s[4] = s[4] / self.static_gain * np.pi\n s[5] = s[5] / self.static_gain * self.vMax\n s[6] = s[6] / self.static_gain * self.vMax\n s[7] = s[7] / self.static_gain * self.omegaMax\n return s\n\n def is_out(self):\n \"\"\"\n :return:\n \"\"\"\n '''简化处理,只判断中心的大圆有没有出界就好'''\n if (self.x + self.rBody > self.x_size) or (self.x - self.rBody < 0) or (self.y + self.rBody > self.y_size) or (self.y - self.rBody < 0):\n return True\n return False\n\n def is_success(self):\n ex = self.terminal[0] - self.x\n ey = self.terminal[1] - self.y\n if np.linalg.norm([ex, ey]) <= self.miss and np.fabs(self.dphi) < deg2rad(1):\n return True\n return False\n\n def is_Terminal(self, param=None):\n # if self.is_out():\n # print('...out...')\n # self.terminal_flag = 1\n # return True\n # if math.fabs(self.initPhi - self.phi) > 2 * math.pi:\n # print('...转的角度太大了...')\n # self.terminal_flag = 1\n # return True\n if self.time > self.timeMax:\n print('...time out...')\n self.terminal_flag = 2\n return True\n # if dis_two_points([self.x, self.y], self.terminal) <= self.miss:\n if self.is_success():\n print('...success...')\n self.terminal_flag = 3\n return True\n self.terminal_flag = 0\n return False\n\n def get_reward(self, param=None):\n cur_s = self.inverse_state_norm(self.current_state)\n nex_s = self.inverse_state_norm(self.next_state)\n\n currentError = math.sqrt(cur_s[0] ** 2 + cur_s[1] ** 2)\n nextError = math.sqrt(nex_s[0] ** 2 + nex_s[1] ** 2)\n\n r1 = -1 # 常值误差,每运行一步,就 -1\n\n # if currentError > nextError + 1e-2:\n # r2 = 3\n # elif 1e-2 + currentError < nextError:\n # r2 = -3\n # else:\n # r2 = 0\n r2 = 0\n # currentTheta = cal_vector_rad([cur_s[0], cur_s[1]], [math.cos(cur_s[4]), math.sin(cur_s[4])])\n # nextTheta = cal_vector_rad([nex_s[0], nex_s[1]], [math.cos(nex_s[4]), math.sin(nex_s[4])])\n # # print(currentTheta, nextTheta)\n # if currentTheta > nextTheta + 1e-3: # 带1e-4是为了\n # r3 = 2\n # elif 1e-3 + currentTheta < nextTheta:\n # r3 = -2\n # else:\n # r3 = 0\n r3 = 0\n '''4. 其他'''\n if self.terminal_flag == 3: # 成功\n r4 = 1000\n elif self.terminal_flag == 2: # 超时\n r4 = -200\n else:\n r4 = 0\n # if self.terminal_flag == 1: # 惩\n # r4 = -200\n '''4. 其他'''\n # print('r1=', r1, 'r2=', r2, 'r3=', r3, 'r4=', r4)\n self.reward = r1 + r2 + r3 + r4\n\n def f(self, _phi):\n _dx = self.r / 2 * (self.wLeft + self.wRight) * math.cos(_phi)\n _dy = self.r / 2 * (self.wLeft + self.wRight) * math.sin(_phi)\n _dphi = self.r / self.rBody * (self.wRight - self.wLeft)\n return np.array([_dx, _dy, _dphi])\n\n def step_update(self, action: list):\n self.wLeft = max(min(action[0], self.wMax), -self.wMax)\n self.wRight = max(min(action[1], self.wMax), -self.wMax)\n self.current_action = action.copy()\n self.current_state = self.state_norm()\n\n '''RK-44'''\n h = self.dt / 10\n t_sim = 0\n state = np.array([self.x, self.y, self.phi])\n while t_sim <= self.dt:\n K1 = self.f(state[2])\n K2 = self.f(state[2] + h * K1[2] / 2)\n K3 = self.f(state[2] + h * K2[2] / 2)\n K4 = self.f(state[2] + h * K3[2])\n state = state + h * (K1 + 2 * K2 + 2 * K3 + K4) / 6\n t_sim += h\n '''动力学系统状态更新'''\n [self.x, self.y, self.phi] = list(state)\n self.dx = self.r / 2 * (self.wLeft + self.wRight) * math.cos(self.phi)\n self.dy = self.r / 2 * (self.wLeft + self.wRight) * math.sin(self.phi)\n self.dphi = self.r / self.rBody * (self.wRight - self.wLeft)\n self.time += self.dt\n '''动力学系统状态更新'''\n '''RK-44'''\n\n '''出界处理'''\n # if self.x + self.rBody > self.x_size: # Xout\n # self.x = self.x_size - self.rBody\n # self.dx = 0\n # if self.x - self.rBody < 0:\n # self.x = self.rBody\n # self.dx = 0\n # if self.y + self.rBody > self.y_size: # Yout\n # self.y = self.y_size - self.rBody\n # self.dy = 0\n # if self.y - self.rBody < 0:\n # self.y = self.rBody\n # self.dy = 0\n '''出界处理'''\n\n if self.phi > np.pi:\n self.phi -= 2 * np.pi\n if self.phi < -np.pi:\n self.phi += 2 * np.pi\n self.is_terminal = self.is_Terminal()\n self.next_state = self.state_norm()\n self.get_reward()\n self.saveData()\n\n def reset(self):\n \"\"\"\n :brief: reset\n :return: None\n \"\"\"\n '''physical parameters'''\n self.x = self.initX # X\n self.y = self.initY # Y\n self.phi = self.initPhi # 车的转角\n self.dx = 0\n self.dy = 0\n self.dphi = 0\n self.wLeft = 0.\n self.wRight = 0.\n self.time = 0. # time\n '''physical parameters'''\n\n '''RL_BASE'''\n self.current_state = self.initial_state.copy()\n self.next_state = self.initial_state.copy()\n self.current_action = self.initial_action.copy()\n self.reward = 0.0\n self.is_terminal = False\n '''RL_BASE'''\n\n '''data_save'''\n self.saveX = [self.x]\n self.saveY = [self.y]\n self.savePhi = [self.phi]\n self.savedX = [self.dx]\n self.savedY = [self.dy]\n self.savedPhi = [self.dphi]\n self.savewLeft = [self.wLeft]\n self.savewRight = [self.wRight]\n '''data_save'''\n\n def reset_random(self):\n \"\"\"\n :return:\n \"\"\"\n '''physical parameters'''\n self.set_terminal([random.uniform(self.L, self.x_size - self.L), random.uniform(self.L, self.y_size - self.L)])\n self.set_start([random.uniform(self.L, self.x_size - self.L), random.uniform(self.L, self.y_size - self.L)])\n # self.x = self.initX # X\n # self.y = self.initY # Y\n self.x = self.start[0]\n self.y = self.start[1]\n self.phi = self.initPhi # 车的转角\n # self.phi = random.uniform(deg2rad(-180), deg2rad(180))\n self.dx = 0\n self.dy = 0\n self.dphi = 0\n self.wLeft = 0.\n self.wRight = 0.\n self.time = 0. # time\n '''physical parameters'''\n\n '''RL_BASE'''\n self.current_state = self.state_norm()\n self.next_state = self.initial_state.copy()\n self.current_action = self.initial_action.copy()\n self.reward = 0.0\n self.is_terminal = False\n '''RL_BASE'''\n\n '''data_save'''\n self.saveX = [self.x]\n self.saveY = [self.y]\n self.savePhi = [self.phi]\n self.savedX = [self.dx]\n self.savedY = [self.dy]\n self.savedPhi = [self.dphi]\n self.savewLeft = [self.wLeft]\n self.savewRight = [self.wRight]\n '''data_save'''\n\n def saveModel2XML(self, filename='UGV_Bidirectional_Continuous.xml', filepath='../config/'):\n rootMsg = {\n 'name': 'UGV_Bidirectional_Continuous',\n 'author': 'Yefeng YANG',\n 'date': '2022.01.11',\n 'E-mail': 'yefeng.yang@connect.polyu.hk; 18B904013@stu.hit.edu.cn'\n }\n rl_baseMsg = {\n 'state_dim': self.state_dim,\n 'state_num': self.state_num,\n 'state_step': self.state_step,\n 'state_space': self.state_space,\n 'state_range': self.state_range,\n 'isStateContinuous': self.isStateContinuous,\n 'initial_state': self.initial_state,\n 'current_state': self.current_state,\n 'next_state': self.next_state,\n 'action_dim': self.action_dim,\n 'action_step': self.action_step,\n 'action_range': self.action_range,\n 'action_num': self.action_num,\n 'action_space': self.action_space,\n 'isActionContinuous': self.isActionContinuous,\n 'initial_action': self.initial_action,\n 'current_action': self.current_action,\n 'is_terminal': self.is_terminal\n }\n physicalMsg = {\n 'initX': self.initX,\n 'initY': self.initY,\n 'initPhi': self.initPhi,\n 'x': self.x,\n 'y': self.y,\n 'phi': self.phi,\n 'dx': self.dx,\n 'dy': self.dy,\n 'dphi': self.dphi,\n 'wLeft': self.wLeft,\n 'wRight': self.wRight,\n 'wMax': self.wMax,\n 'r': self.r,\n 'l_wheel': self.l_wheel,\n 'rBody': self.rBody,\n 'L': self.L,\n 'dt': self.dt,\n 'time': self.time,\n 'x_size': self.x_size,\n 'y_size': self.y_size,\n 'miss': self.miss\n }\n imageMsg = {\n 'width': self.width,\n 'height': self.height,\n 'name4image': self.name4image,\n 'x_offset': self.x_offset,\n 'y_offset': self.y_offset,\n 'pixel_per_meter': self.pixel_per_meter\n }\n xml_cfg().XML_Create(filename=filepath + filename,\n rootname='Plant',\n rootmsg=rootMsg)\n xml_cfg().XML_InsertNode(filename=filepath + filename,\n nodename='RL_Base',\n nodemsg=rl_baseMsg)\n xml_cfg().XML_InsertNode(filename=filepath + filename,\n nodename='Physical',\n nodemsg=physicalMsg)\n xml_cfg().XML_InsertNode(filename=filepath + filename,\n nodename='Image',\n nodemsg=imageMsg)\n xml_cfg().XML_Pretty_All(filepath + filename)\n\n def saveData(self, is2file=False, filename='Two_Wheel_UGV.csv', filepath=''):\n if is2file:\n data = pd.DataFrame({\n 'x:': self.saveX,\n 'y': self.saveY,\n 'phi': self.savePhi,\n 'dx': self.savedX,\n 'dy': self.savedY,\n 'dphi': self.savedPhi,\n 'wLeft': self.savewLeft,\n 'wRight': self.savewRight,\n 'time': self.saveTime\n })\n data.to_csv(filepath + filename, index=False, sep=',')\n else:\n self.saveX = [self.x]\n self.saveY = [self.y]\n self.savePhi = [self.phi]\n self.savedX = [self.dx]\n self.savedY = [self.dy]\n self.savedPhi = [self.dphi]\n self.savewLeft = [self.wLeft]\n self.savewRight = [self.wRight]\n self.saveTime = [self.time]\n","repo_name":"ReinforcementLearning-StudyNote/ReinforcementLearning","sub_path":"environment/envs/UGV/ugv_bidirectional_continuous.py","file_name":"ugv_bidirectional_continuous.py","file_ext":"py","file_size_in_byte":19226,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"80"} +{"seq_id":"25124168990","text":"from threading import Thread\nimport device\nimport matplotlib.animation as animation\nimport matplotlib.pyplot as plt\n\n\ncolors = ['red', 'green', 'blue', 'black']\n\n\ndef real_time_plot(fig, buffers, sub_plots):\n for i in range(len(buffers)):\n sub_plots[i].clear()\n sub_plots[i].plot(buffers[i], color=colors[i % len(colors)])\n\n\ndef main():\n\n # Reads from the user the serial port to read from\n port = input(\"Insert the serial directory [/dev/ttyACM0]: \")\n if len(port) == 0:\n port = \"/dev/ttyACM0\"\n\n length = input(\"Specify the x-axis length [100]: \")\n try:\n length = int(length)\n if length < 0:\n length = 100\n except ValueError:\n length = 100\n\n num_values = device.initialize_serial(port)\n\n buffers = []\n for i in range(num_values):\n buffers.append([0 for i in range(length)])\n\n fig = plt.figure()\n\n sub_plots = []\n for i in range(num_values):\n sub_plots.append(fig.add_subplot(num_values+1, 1, i+1))\n\n Thread(target=device.read_from_serial, args=(buffers,)).start()\n a = animation.FuncAnimation(fig, real_time_plot, fargs=(buffers, sub_plots), interval=10)\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"TestaDiRapa/turnip-plotter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"35508357337","text":"'''tkinter Tcl/Tk GUI for the Bay Assessment Model (BAM)'''\n\n# Python distribution modules\nfrom subprocess import Popen\nfrom datetime import timedelta, datetime\nfrom collections import OrderedDict as odict\nfrom os.path import exists as path_exists\nfrom random import randint\n\nstrptime = datetime.strptime\n\n# Note that these are separate modules:\n# tkinter.filedialog\n# tkinter.messagebox\n# tkinter.font\nimport tkinter as Tk\nfrom tkinter import messagebox\nfrom tkinter import filedialog\nfrom tkinter import ttk # tk themed widgets within tkinter (tkinter.ttk)\n\n# Community modules\nfrom numpy import linspace, isnan\nfrom numpy import all as npall\nfrom numpy import NaN as npNaN\n\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib.colors import BoundaryNorm\nfrom matplotlib.colorbar import ColorbarBase\n\n# These matplotlib objects are only used in MouseClick \nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Polygon\n# Used in PlotData\nfrom matplotlib.dates import YearLocator, MonthLocator, DayLocator\nfrom matplotlib.dates import DateFormatter\nfrom matplotlib.pyplot import cm\n# Modules to embed matplotlib figure in a Tkinter window, see:\n# http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.backends._backend_tk import NavigationToolbar2Tk\n\n# Local modules \nfrom init import InitTimeBasins\nfrom init import GetBasinSalinityData\nfrom init import GetBasinStageData\nfrom init import GetTimeIndex\nimport constants\n\n#---------------------------------------------------------------\n# \n#---------------------------------------------------------------\nclass GUI:\n '''GUI : tkinter & ttk with embedded matplotlib figure.'''\n\n def __init__( self, root, model ):\n\n self.model = model\n \n # GUI objects\n self.Tk_root = root\n self.figure = None # matplotlib figure set onto canvas\n self.figure_axes = None # \n self.canvas = None # \n self.colorbar = None # legend\n self.basinListBox = None # in the mainframe\n self.basinListBoxMap = dict() # { basin name : listbox index }\n self.shoalListBox = None # a Toplevel pop-up\n self.gaugeListBox = None # a Toplevel pop-up\n self.msgText = None # Tk.Text widget for gui messages\n\n self.buttonStyle = ttk.Style() # Note that BAM.TButton is child class\n self.buttonStyle.configure( 'BAM.TButton', font = constants.buttonFont )\n self.checkButtonStyle = ttk.Style() \n self.checkButtonStyle.configure('BAM.TCheckbutton',\n font = constants.textFont )\n \n self.mapOptionMenu = None # map plot variable selection\n self.plotOptionMenu = None # timeseries plot variable selection\n self.startTimeEntry = None # simulation start time\n self.endTimeEntry = None # simulation end time\n\n self.plotVar_IntVars = odict() # { plotVariable : Tk.IntVar() }\n \n if not self.model.args.noGUI :\n # Set Tk-wide Font default for filedialog\n # But it doesn't set filedialog window or button fonts\n #root.tk.call( \"option\", \"add\", \"*Font\", constants.textFont ) \n root.option_add( \"*Font\", constants.textFont )\n\n self.mapPlotVariable = Tk.StringVar()\n self.plotVariable = Tk.StringVar()\n self.current_time_label = Tk.StringVar()\n self.start_text = Tk.StringVar( value = model.args.start )\n self.end_text = Tk.StringVar( value = model.args.end )\n\n self.plot_dir = model.args.basinOutputDir\n self.last_plot_dir = self.plot_dir\n\n # matplotlib colors can be names ('red', 'blue', 'green') or \n # R, G, B tuple in the range [0,1] or fraction of gray in [0,1] '0.5'\n # These 10 colors define the legend and map color ranges\n self.colors = [ [ 0., 0., 1. ], [ 0., .2, 1. ], \n [ 0., .4, 1. ], [ 0., .6, 1. ],\n [ 0., .8, 1. ], [ 1., .8, 0. ],\n [ 1., .6, 0. ], [ 1., .4, 0. ],\n [ 1., .2, 0. ], [ 1., 0., 0. ] ]\n\n #------------------------------------------------------------------\n #\n #------------------------------------------------------------------\n def FloridaBayModel_Tk ( self ) :\n '''User interface for the Florida Bay Model'''\n\n icon = None\n\n try :\n icon = Tk.PhotoImage( file = self.model.args.path +\\\n 'data/init/PyFBM_icon.png' )\n except :\n icon = Tk.PhotoImage( file = self.model.args.path +\\\n 'data/init/PyFBM_icon.gif' )\n\n if icon :\n self.Tk_root.iconphoto( True, icon )\n\n # Create the main widget Frame (window) and a control frame\n mainframe = ttk.Frame( self.Tk_root, padding = \"3 3 3 3\" )\n controlframe = ttk.Frame( self.Tk_root, padding = \"1 1 1 1\" )\n \n # Create matplotlib figure and the canvas it is rendered onto\n self.figure = Figure( figsize = (5, 4), # width x height (in)\n dpi = 150, \n facecolor = 'grey' )\n\n self.figure_axes = self.figure.add_axes( ( 0, 0, 1, 1 ), \n frameon = False,\n label = 'FloridaBayModel' )\n \n # Map limits are UTM Zone 17R in (m)\n self.figure_axes.set_xlim( ( 490000, 569000 ) )\n self.figure_axes.set_ylim( ( 2742000, 2799000 ) )\n\n self.canvas = FigureCanvasTkAgg( self.figure, master = mainframe )\n\n self.canvas.mpl_connect( 'pick_event', self.MouseClick )\n\n # Setup the menu bar\n menuBar = Tk.Menu( self.Tk_root )\n self.Tk_root.config( menu = menuBar )\n # File Menu -----------------------------------------------\n menuFile = Tk.Menu( menuBar, tearoff=False, font = constants.textFont )\n menuBar.add_cascade( menu = menuFile, label = ' File ', \n font = constants.textFont )\n menuFile.add_command( label = ' Init', command = self.OpenInitFile )\n menuFile.add_command( label = ' Edit', command = self.EditFile )\n # Dir Menu -----------------------------------------------\n menuDir = Tk.Menu( menuBar, tearoff=False, font = constants.textFont )\n menuBar.add_cascade( menu = menuDir, label = ' Dir ', \n font = constants.textFont )\n menuDir.add_command( label = 'Plot Disk', command = self.GetPlotDir )\n menuDir.add_command( label = ' Output ', command = self.GetOutputDir )\n # Help Menu -----------------------------------------------\n menuHelp = Tk.Menu( menuBar, tearoff=False, font = constants.textFont )\n menuBar.add_cascade( menu = menuHelp, label = 'Help', \n font = constants.textFont )\n menuHelp.add_command( label = 'About', command = self.ShowAboutInfo )\n\n # Entry for start and end time, register CheckTimeEntry validatecommand\n checkTimeCommand = controlframe.register( self.CheckTimeEntry )\n\n self.startTimeEntry = ttk.Entry( mainframe, width = 15, \n font = constants.textFont,\n justify = Tk.LEFT, \n textvariable = self.start_text,\n validatecommand = ( checkTimeCommand, \n '%P', '%W' ),\n validate = 'focusout' )\n\n self.endTimeEntry = ttk.Entry( mainframe, width = 15, \n font = constants.textFont,\n justify = Tk.LEFT, \n textvariable = self.end_text,\n validatecommand = ( checkTimeCommand, \n '%P', '%W' ),\n validate = 'focusout' )\n\n # Current model time\n currentTimeLabel = Tk.Label( mainframe, width = 18, height = 1, \n bg = 'white',\n font = constants.textFont,\n justify = Tk.CENTER, \n textvariable = self.current_time_label )\n\n # Text box for messages\n self.msgText = Tk.Text( mainframe, height = 5,\n background='white', font = constants.textFont )\n self.Message( self.model.Version )\n self.Message( self.model.args.commandLine + '\\n' )\n \n msgScrollBar = ttk.Scrollbar( mainframe, orient = Tk.VERTICAL, \n command = self.msgText.yview )\n\n self.msgText.configure( yscrollcommand = msgScrollBar.set )\n\n # Basin Listbox\n self.basinListBox = Tk.Listbox( mainframe, height = 5, width = 20, \n selectmode = Tk.EXTENDED, \n font = constants.textFont )\n\n # Insert the basin names into the Listbox\n # The listvariable = [] option won't work if\n # there is whitespace in a name, so insert them manually\n i = 0\n for Basin in self.model.Basins.values() :\n self.basinListBox.insert( i, Basin.name )\n self.basinListBoxMap[ Basin.name ] = i\n i = i + 1\n\n # Listbox vertical scroll bar : calls model.basinListBox.yview\n scrollBar = ttk.Scrollbar( mainframe, orient = Tk.VERTICAL, \n command = self.basinListBox.yview )\n\n # Tell the Listbox that it will scroll according to the scrollBar\n self.basinListBox.configure( yscrollcommand = scrollBar.set )\n\n # Listbox calls ProcessBasinListbox() when selection changes\n self.basinListBox.bind('<>', self.ProcessBasinListbox)\n\n # Colorize alternating lines of the listbox\n for i in range( 0, len( self.model.Basins.keys() ), 2):\n self.basinListBox.itemconfigure( i, background = '#f0f0ff' )\n \n #--------------------------------------------------------------------\n # These widgets are in the control frame\n # OptionMenu for map plot types\n self.mapPlotVariable.set( constants.BasinMapPlotVariable[0] )\n\n self.mapOptionMenu = Tk.OptionMenu( controlframe, \n self.mapPlotVariable,\n *constants.BasinMapPlotVariable )\n\n self.mapOptionMenu.config ( font = constants.buttonFont )\n self.mapOptionMenu['menu'].config( font = constants.buttonFont )\n self.mapOptionMenu.config( bg = 'white' )\n\n # Button for self.Init()\n initButton = ttk.Button( controlframe, text = \"Init\",\n style = 'BAM.TButton',\n command = lambda : InitTimeBasins(self.model))\n\n # Button for model.Run()\n runButton = ttk.Button( controlframe, text = \"Run\",\n style = 'BAM.TButton',\n command = self.model.Run )\n\n # Button for model.Pause()\n pauseButton = ttk.Button( controlframe, text = \"Pause\",\n style = 'BAM.TButton',\n command = self.model.Pause )\n\n # Button for model.Stop()\n stopButton = ttk.Button( controlframe, text = \"Stop\",\n style = 'BAM.TButton',\n command = self.model.Stop )\n\n # Button for model.GetRecordVariables()\n recordVarButton = ttk.Button( controlframe, text = \"Record\",\n style = 'BAM.TButton',\n command = self.GetRecordVariables )\n\n # OptionMenu for variable timeseries plot types\n self.plotVariable.set( constants.BasinPlotVariable[0] )\n\n self.plotOptionMenu = Tk.OptionMenu( controlframe, self.plotVariable,\n *constants.BasinPlotVariable )\n \n self.plotOptionMenu.config ( font = constants.buttonFont )\n self.plotOptionMenu['menu'].config( font = constants.buttonFont )\n self.plotOptionMenu.config( bg = 'white' )\n\n # Button for model.PlotRunData()\n plotRunButton = ttk.Button( controlframe, text = \"Plot Run\",\n style = 'BAM.TButton',\n command = self.PlotRunData )\n\n # Button for model.PlotArchiveData()\n plotArchiveButton = ttk.Button( controlframe, text = \"Plot Disk\",\n style = 'BAM.TButton',\n command = self.PlotArchiveData )\n\n # Button for PlotGaugeSalinityData()\n # Can't set text color in ttk Button, use standard Tk\n plotGaugeSalinityButton = Tk.Button( controlframe, text = \"Salinity\",\n command = self.PlotGaugeSalinityData,\n font = constants.buttonFont,\n foreground = 'blue' )\n \n # Button for PlotGaugeStageData()\n # Can't set text color in ttk Button, use standard Tk\n plotGaugeStageButton = Tk.Button( controlframe, text = \"Stage\",\n command = self.PlotGaugeStageData,\n font = constants.buttonFont,\n foreground = 'blue' )\n \n #-------------------------------------------------------------------\n # Setup the window layout with the 'grid' geometry manager. \n # The value of the \"sticky\" option is a string of 0 or more of the \n # compass directions N S E W, specifying which edges of the cell the \n # widget should be \"stuck\" to.\n mainframe.grid( row = 0, column = 0, sticky = (Tk.N, Tk.W, Tk.E, Tk.S) )\n \n controlframe.grid( in_ = mainframe, row = 1, column = 1, \n rowspan = 3, sticky = (Tk.N, Tk.S) )\n\n #-------------------------------------------------------------------\n # Grid all the widgets - This is the layout of the window\n # This application has 5 columns and 4 rows\n # Column 1 row 1 has the controlframe with its own grid manager\n # col 0 | col 1 | col 2 | col 3 | col 4\n # row 0 Basin List | <----------- Message Text -----------> \n # row 1 \\/ | Controls | Model Time | Start | End \n # row 2 \\/ | \\/ | <---------- Map --------->\n # row 3 \\/ | \\/ | \\/\n #\n #-------------------------------------------------------------------\n self.basinListBox.grid( column = 0, row = 0, rowspan = 4, \n sticky = (Tk.N,Tk.S,Tk.W,Tk.E) )\n \n scrollBar.grid( column = 0, row = 0, rowspan = 4, \n sticky = (Tk.E,Tk.N,Tk.S) )\n\n self.msgText.grid( column = 1, row = 0, columnspan = 4,\n sticky = (Tk.N,Tk.S,Tk.W,Tk.E) )\n\n msgScrollBar.grid( column = 4, row = 0, \n sticky = (Tk.E,Tk.N,Tk.S) )\n\n currentTimeLabel.grid ( column = 2, row = 1 )\n self.startTimeEntry.grid ( column = 3, row = 1 )\n self.endTimeEntry.grid ( column = 4, row = 1 )\n \n #-------------------------------------------------------------\n # controlframe.grid is set above\n self.mapOptionMenu.grid( in_ = controlframe, row = 0 )\n initButton.grid ( in_ = controlframe, row = 1 )\n runButton.grid ( in_ = controlframe, row = 2 )\n pauseButton.grid ( in_ = controlframe, row = 3 )\n stopButton.grid ( in_ = controlframe, row = 4 )\n\n ttk.Separator( orient = Tk.HORIZONTAL ).grid( in_ = controlframe, \n row = 5, pady = 5,\n sticky = (Tk.E,Tk.W) )\n\n recordVarButton.grid ( in_ = controlframe, row = 6 )\n\n ttk.Separator( orient = Tk.HORIZONTAL ).grid( in_ = controlframe, \n row = 7, pady = 5,\n sticky = (Tk.E,Tk.W) )\n\n self.plotOptionMenu.grid( in_ = controlframe, row = 8 )\n plotRunButton.grid ( in_ = controlframe, row = 9 )\n plotArchiveButton.grid ( in_ = controlframe, row = 10 )\n\n ttk.Separator( orient = Tk.HORIZONTAL ).grid( in_ = controlframe, \n row = 11, pady = 5,\n sticky = (Tk.E,Tk.W) )\n\n plotGaugeSalinityButton.grid( in_ = controlframe, row = 12,\n sticky = (Tk.E,Tk.W) )\n plotGaugeStageButton.grid ( in_ = controlframe, row = 13,\n sticky = (Tk.E,Tk.W) )\n #-------------------------------------------------------------\n \n self.canvas.get_tk_widget().grid ( column = 2, row = 2, \n columnspan = 3, rowspan = 2,\n sticky = (Tk.N,Tk.S,Tk.W,Tk.E) )\n \n # For each widget in the mainframe, set some padding around\n # the widget to space things out and look better\n for child in mainframe.winfo_children():\n child.grid_configure( padx = 2, pady = 2 )\n\n # Add a Sizegrip to make resizing easier.\n #ttk.Sizegrip( mainframe ).grid( column = 99, row = 99, \n # sticky = (Tk.N,Tk.S,Tk.E,Tk.W))\n\n # Setup the resize control with the 'grid' geometry manager. \n # Every column and row has a \"weight\" grid option associated with it, \n # which tells it how much it should grow if there is extra room in \n # the master to fill. By default, the weight of each column or row \n # is 0, meaning don't expand to fill space. Here we set the weight\n # to 1 telling the widget to expand and fill space as the window \n # is resized. \n # Make Sure to set on the root window!!!\n self.Tk_root.columnconfigure( 0, weight = 1 )\n self.Tk_root.rowconfigure ( 0, weight = 1 )\n\n mainframe.columnconfigure( 0, weight = 0 )\n mainframe.columnconfigure( 1, weight = 0 )\n mainframe.columnconfigure( 2, weight = 1 )\n #mainframe.columnconfigure( 3, weight = 1 )\n #mainframe.columnconfigure( 4, weight = 1 )\n\n mainframe.rowconfigure ( 0, weight = 1 )\n mainframe.rowconfigure ( 1, weight = 0 )\n mainframe.rowconfigure ( 2, weight = 1 ) \n mainframe.rowconfigure ( 3, weight = 1 )\n \n # MapPlotVarUpdate() will refresh the legend on mapPlotVariable changes\n self.mapPlotVariable.trace( 'w', self.MapPlotVarUpdate )\n\n self.RenderShoals( init = True )\n self.PlotLegend( \"FloridaBayModel\" )\n self.canvas.draw()\n\n #------------------------------------------------------------------\n #\n #------------------------------------------------------------------\n def Message ( self, msg ) :\n '''Display message in msgText box or on console, log to run_info.'''\n if not self.model.args.noGUI :\n self.msgText.insert( Tk.END, msg )\n self.msgText.see ( Tk.END )\n else :\n print( msg, end = '' )\n\n self.model.run_info.append( msg )\n\n #------------------------------------------------------------------\n #\n #------------------------------------------------------------------\n def MapPlotVarUpdate ( self, *args ) :\n '''User has changed mapPlotVariable, update the legend.'''\n if self.model.args.DEBUG_ALL :\n print( '-> MapPlotVarUpdate: ', args[0], ', ', args[2] )\n\n self.PlotLegend( \"MapPlotVarUpdate\" )\n self.canvas.draw()\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def InitPlotVars( self ):\n '''Create map of plotVariables and Tk.IntVar() to associate\n with the checkButtons accessed in GetRecordVariables(). These\n Tk.IntVars are held in the plotVar_IntVars map, and read in\n SetRecordVariables() to determine which variables will be\n recorded into the basin.plot_variables maps for eventual\n plotting and archiving'''\n\n if self.model.args.DEBUG_ALL :\n print( '-> InitPlotVars' )\n\n self.plotVar_IntVars.clear()\n\n for plotVariable in constants.BasinPlotVariable :\n if not self.model.args.noGUI :\n self.plotVar_IntVars[ plotVariable ] = Tk.IntVar()\n else :\n # Use the IntVar() class defined below\n self.plotVar_IntVars[ plotVariable ] = IntVar()\n\n # Set Salinity, Stage, Flow, Volume, Rain, ET as defaults\n self.plotVar_IntVars[ 'Salinity' ].set( 1 )\n self.plotVar_IntVars[ 'Stage' ].set( 1 )\n self.plotVar_IntVars[ 'Flow' ].set( 1 )\n self.plotVar_IntVars[ 'Volume' ].set( 1 )\n self.plotVar_IntVars[ 'Rain' ].set( 1 )\n self.plotVar_IntVars[ 'Evaporation' ].set( 1 )\n self.plotVar_IntVars[ 'Runoff' ].set( 1 )\n\n # Initialize the basin.plot_variables\n for plotVariable, intVar in self.plotVar_IntVars.items() :\n\n for basin in self.model.Basins.values() :\n basin.plot_variables.clear()\n\n if intVar.get() :\n basin.plot_variables[ plotVariable ] = []\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def GetRecordVariables( self ):\n '''Pop up checkbuttons to select basin variables to record'''\n\n if self.model.args.DEBUG_ALL :\n print( '-> GetRecordVariables' )\n\n #-------------------------------------------------------\n # A top level pop up widget\n top = Tk.Toplevel()\n top.wm_title( 'Variables' )\n top.minsize( width = 150, height = 100 )\n\n top.grid()\n\n setButton = ttk.Button( top, text = \"Set\",\n style = 'BAM.TButton',\n command = self.SetRecordVariables )\n\n closeButton = ttk.Button( top, text = \"Close\",\n style = 'BAM.TButton',\n command = lambda: top.destroy() )\n\n checkButtons = odict()\n\n for plotVariable in constants.BasinPlotVariable :\n checkButtons[ plotVariable ] = \\\n ttk.Checkbutton( top, text = plotVariable,\n style = 'BAM.TCheckbutton',\n variable = self.plotVar_IntVars[plotVariable])\n\n for checkButton in checkButtons.values() :\n checkButton.grid( sticky = Tk.W, \n padx = 30, pady = 3 )\n\n setButton.grid ( padx = 15, pady = 2 )\n closeButton.grid( padx = 15, pady = 2 )\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def SetRecordVariables( self ):\n '''Callback method for Set button in GetRecordVariables().\n Sets the basin.plot_variables entries based on the selected\n plotVariable checkboxes in GetRecordVariables()'''\n\n if self.model.args.DEBUG_ALL :\n print( '-> SetRecordVariables' )\n for plotVariable, intVar in self.plotVar_IntVars.items() :\n print( plotVariable, ' : ', intVar, '=', intVar.get() )\n \n # Reset time and basins\n InitTimeBasins( self.model )\n msg ='*** All records erased, time reset to start time, basins reset.\\n'\n self.Message( msg )\n\n for plotVariable, intVar in self.plotVar_IntVars.items() :\n\n for basin in self.model.Basins.values() :\n basin.plot_variables.clear()\n\n if intVar.get() :\n basin.plot_variables[ plotVariable ] = []\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def PlotRunData( self ) :\n '''Plot data for selected basins from the current simulation.'''\n\n if self.model.args.DEBUG_ALL :\n print( '-> PlotRunData', flush = True )\n\n # Get a list of Basins from the Listbox\n BasinList = self.GetBasinListbox()\n\n if len( BasinList ) == 0 :\n msg = '\\nPlotRunData: No basins are selected.\\n'\n self.Message( msg )\n return\n\n # Get the plotVariable type from the plotOptionMenu\n plotVariable = self.plotVariable.get()\n\n # Get the data\n dataList = []\n basinNames = []\n\n for Basin in BasinList :\n if plotVariable not in Basin.plot_variables.keys() :\n msg = '\\nPlotRunData: ' + plotVariable + ' data ' +\\\n 'is not present for basin ' + Basin.name + '.\\n'\n self.Message( msg )\n return\n\n dataList.append( Basin.plot_variables[ plotVariable ] )\n basinNames.append( Basin.name )\n\n self.PlotData( self.model.times, dataList, basinNames, plotVariable,\n period_record_days = self.model.simulation_days )\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def PlotArchiveData( self ) :\n '''Plot data from a previous run stored on disk.'''\n\n if self.model.args.DEBUG :\n print( '-> PlotArchiveData', flush = True )\n\n # Get a list of Basins from the Listbox\n BasinList = self.GetBasinListbox()\n\n if len( BasinList ) == 0 :\n msg = '\\nPlotArchiveData: No basins are selected.\\n'\n self.Message( msg )\n return\n\n self.last_plot_dir = self.plot_dir\n \n if self.model.args.DEBUG :\n print( self.plot_dir )\n\n # Get the data into \n all_times = []\n times = []\n basinNames = []\n dataList = []\n\n # Get the plotVariable type from the plotOptionMenu\n plotVariable = self.plotVariable.get()\n\n for Basin in BasinList :\n\n basinNames.append( Basin.name )\n\n # Read the basin .csv data to get [times] and [data]\n file_name = self.plot_dir + '/' + \\\n Basin.name + self.model.args.runID + '.csv'\n try :\n fd = open( file_name, 'r' )\n except OSError as err :\n msg = \"\\nPlotArchiveData: OS error: {0}\\n\".format( err )\n self.Message( msg )\n return\n\n rows = fd.readlines()\n fd.close()\n\n # Time, Stage (m), Flow (m^3/t), Salinity (ppt),\tVolume (m^3)\n # 2000-01-01 00:00:00, 0.0, 0.0, 37.0,\t52475622.557\n # 2000-01-01 01:00:00, -0.0, 45.772, 37.0,\t52459564.487\n variables = rows[ 0 ].split(',')\n for i in range( len( variables ) ) :\n variables[ i ] = variables[ i ].strip()\n\n # column index for Time\n time_col_i = variables.index( 'Time' )\n\n # column index for plotVariable\n try :\n unit_str = constants.PlotVariableUnit[ plotVariable ]\n data_col_i = variables.index( plotVariable + ' ' + unit_str )\n\n except ValueError as err :\n msg = \"\\nPlotArchiveData: {0}\\n\".format( err )\n self.Message( msg )\n return\n\n # Get all times in file from first Basin in BasinList\n if Basin == BasinList[ 0 ] :\n for i in range( 1, len( rows ) ) :\n words = rows[ i ].split(',')\n time_i = datetime.strptime( words[ time_col_i ].strip(),\n '%Y-%m-%d %H:%M:%S' )\n all_times.append( time_i )\n\n # Find index in dates for start_time & end_time\n start_i, end_i = GetTimeIndex( plotVariable, all_times,\n self.model.start_time, \n self.model.end_time )\n\n # Populate only data needed for the simulation timeframe\n times = all_times[ start_i : end_i + 1 ]\n data = []\n for i in range( start_i, end_i + 1 ) :\n row = rows[ i + 1 ]\n words = row.split(',')\n\n value_string = words[ data_col_i ]\n\n if 'NA' in value_string :\n data.append( npNaN )\n else :\n data.append( float( value_string ) )\n\n # If data is all NA don't plot\n if npall( isnan( data ) ) :\n msg = \"\\nPlotArchiveData: \" + plotVariable + ' for basin ' +\\\n Basin.name + ' does not exist.\\n'\n self.Message( msg )\n else :\n dataList.append( data )\n\n period_record = times[ len( times ) - 1 ] - times[ 0 ] # timedelta\n\n self.PlotData( times, dataList, basinNames, plotVariable,\n period_record_days = period_record.days,\n path = ' from: ' + self.plot_dir )\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def PlotGaugeSalinityData( self ) :\n '''Plot salinity data from gauge observations.'''\n\n if self.model.args.DEBUG :\n print( '-> PlotGaugeSalinityData', flush = True )\n\n BasinList = self.GetBasinListbox()\n\n if len( BasinList ) == 0 :\n msg = '\\nPlotGaugeSalinityData: No basins are selected.\\n'\n self.Message( msg )\n return\n\n basin_names = [ Basin.name for Basin in BasinList ]\n\n # Read the salinity .csv gauge data to get [times] and [data]\n if not self.model.salinity_data :\n GetBasinSalinityData( self.model )\n\n # plotVariables are salinity stations IDs : 'MD', 'GB'...\n plotVariables = []\n for Basin in BasinList :\n if Basin.salinity_station :\n plotVariables.append( Basin.salinity_station )\n\n # Get times[] from model.salinity_data.keys()\n times = [ datetime( year = key_tuple[0], \n month = key_tuple[1], \n day = key_tuple[2] )\n for key_tuple in self.model.salinity_data.keys() ]\n\n # Get data\n dataList = []\n for plotVariable in plotVariables :\n data = []\n for key in self.model.salinity_data.keys() :\n data.append( self.model.salinity_data[key][plotVariable] )\n dataList.append( data )\n\n if not dataList :\n msg = 'No salinity gauge data for these basins.\\n'\n self.Message( msg )\n return\n\n period_record = times[ -1 ] - times[ 0 ] # timedelta\n\n self.PlotData( times, dataList,\n basinNames = basin_names,\n plotVariable = 'Salinity',\n period_record_days = period_record.days,\n title = 'Gauge: ',\n path = ' from: ' + self.model.args.salinityFile )\n\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def PlotGaugeStageData( self ) :\n '''Plot stage data from gauge observations.'''\n\n if self.model.args.DEBUG :\n print( '-> PlotGaugeStageData', flush = True )\n\n BasinList = self.GetBasinListbox()\n\n if len( BasinList ) == 0 :\n msg = '\\nPlotGaugeStageData: No basins are selected.\\n'\n self.Message( msg )\n return\n\n basin_names = [ Basin.name for Basin in BasinList ]\n\n # Read the stage .csv gauge data to get [times] and [data]\n if not self.model.stage_data :\n GetBasinStageData( self.model )\n\n # plotVariables are stations IDs : 'MD', 'GB'...\n # which are the same as the salinity_station\n plotVariables = []\n for Basin in BasinList :\n if Basin.salinity_station :\n plotVariables.append( Basin.salinity_station )\n\n # Get times[] from model.salinity_data.keys()\n times = [ datetime( year = key_tuple[0], \n month = key_tuple[1], \n day = key_tuple[2] )\n for key_tuple in self.model.stage_data.keys() ]\n\n # Get data\n dataList = []\n for plotVariable in plotVariables :\n data = []\n for key in self.model.stage_data.keys() :\n try :\n data.append( self.model.stage_data[ key ][ plotVariable ] )\n except KeyError : \n msg = 'No stage gauge data for ' + plotVariable + '.\\n'\n self.Message( msg )\n break\n\n if data :\n dataList.append( data )\n\n if not dataList :\n msg = 'No stage gauge data for these basins.\\n'\n self.Message( msg )\n return\n\n period_record = times[ -1 ] - times[ 0 ] # timedelta\n\n self.PlotData( times, dataList,\n basinNames = basin_names,\n plotVariable = 'Stage',\n period_record_days = period_record.days,\n title = 'Gauge: ',\n path = ' from: ' + self.model.args.basinStage )\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def PlotData( self, time, dataList, basinNames, plotVariable, \n period_record_days, title = 'Basins: ', path = '' ) :\n ''' '''\n\n if self.model.args.DEBUG_ALL :\n print( '-> PlotData', flush = True )\n\n for Basin in BasinList :\n print( '\\t', Basin.name, '\\t: ', plotVariable )\n\n if not len( dataList ) or not len( time ):\n return\n\n #-------------------------------------------------------\n # A top level pop up widget\n top = Tk.Toplevel()\n top.wm_title( title + plotVariable + path )\n\n colors = iter( cm.rainbow( linspace( 0, 1, len( dataList ) ) ) )\n color = next( colors )\n\n figure = Figure( figsize = ( 8, 5 ), dpi = 100 )\n axes = figure.add_subplot( 111, label = \"PlotData\" )\n\n axes.plot( time, dataList[ 0 ], label = basinNames[ 0 ],\n linewidth = 2, color = color )\n\n for i in range( 1, len( dataList ) ) :\n color = next( colors )\n axes.plot( time, dataList[ i ], \n label = basinNames[ i ],\n linewidth = 2, color = color )\n\n axes.set_xlabel( 'Date' )\n axes.set_ylabel( plotVariable + ' ' +\\\n constants.PlotVariableUnit[ plotVariable ] )\n axes.fmt_xdata = DateFormatter('%Y-%m-%d')\n \n # matplotlib does not default ticks well... arghhh\n if period_record_days < 15 :\n axes.xaxis.set_major_locator ( DayLocator() )\n axes.xaxis.set_major_formatter( DateFormatter('%d') )\n\n elif period_record_days < 91 :\n axes.xaxis.set_major_locator ( MonthLocator() )\n axes.xaxis.set_major_formatter( DateFormatter('%m-%d') )\n axes.xaxis.set_minor_locator ( DayLocator(bymonthday=[7,14,21]))\n axes.xaxis.set_minor_formatter( DateFormatter('%d') )\n\n elif period_record_days < 181 :\n axes.xaxis.set_major_locator ( MonthLocator() )\n axes.xaxis.set_major_formatter( DateFormatter('%b-%d') )\n axes.xaxis.set_minor_locator ( DayLocator(bymonthday=[15]))\n axes.xaxis.set_minor_formatter( DateFormatter('%d') )\n\n elif period_record_days < 366 :\n axes.xaxis.set_major_locator ( MonthLocator() )\n axes.xaxis.set_major_formatter( DateFormatter('%b') )\n\n elif period_record_days < 731 :\n axes.xaxis.set_major_locator ( YearLocator() )\n axes.xaxis.set_major_formatter( DateFormatter('%Y') )\n axes.xaxis.set_minor_locator ( MonthLocator(bymonth=[3,5,7,9,11]))\n axes.xaxis.set_minor_formatter( DateFormatter('%b') )\n\n elif period_record_days < 1826 :\n axes.xaxis.set_major_locator ( YearLocator() )\n axes.xaxis.set_major_formatter( DateFormatter('%Y') )\n axes.xaxis.set_minor_locator ( MonthLocator(bymonth=[7]) )\n axes.xaxis.set_minor_formatter( DateFormatter('%b') )\n\n else :\n axes.xaxis.set_major_locator ( YearLocator() )\n axes.xaxis.set_major_formatter( DateFormatter('%Y') )\n\n legend = axes.legend( loc = 'upper center', fontsize = 9,\n frameon = False, labelspacing = None )\n\n #figure.autofmt_xdate( bottom = 0.2, rotation = 90 )\n figure.set_tight_layout( True ) # tight_layout()\n\n # Tk.DrawingArea\n canvas = FigureCanvasTkAgg( figure, master = top )\n\n try :\n canvas.draw()\n except RuntimeError as err :\n msg = \"\\nPlotData: {0}. \\n\".format( err ) +\\\n \" Try setting the start/end time to cover the data record.\\n\"\n self.Message( msg )\n top.destroy()\n return\n\n canvas.get_tk_widget().pack( side = Tk.TOP, fill = Tk.BOTH, \n expand = True )\n\n toolbar = NavigationToolbar2Tk( canvas, top )\n toolbar.update()\n canvas._tkcanvas.pack( side = Tk.TOP, fill = Tk.BOTH, expand = True )\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def RenderBasins( self, init = False ):\n ''' '''\n\n for Basin in self.model.Basins.values() :\n\n if Basin.boundary_basin :\n continue\n\n basin_xy = Basin.basin_xy\n\n if basin_xy is None :\n continue\n\n basin_name = Basin.name\n\n if init :\n # Initialize Basin.color with salinity color\n Basin.SetBasinMapColor( 'Salinity', \n self.model.args.salinity_legend_bounds )\n\n if not Basin.Axes_fill : \n PolygonList = self.figure_axes.fill( \n basin_xy[:,0], basin_xy[:,1], \n fc = Basin.color, \n ec = 'white', \n zorder = -1, \n picker = True,\n label = basin_name ) # NOTE: this is a list...!\n\n Basin.Axes_fill = PolygonList[ 0 ] \n\n else :\n # Don't call fill() again if not init, it creates a new Polygon\n Basin.Axes_fill.set_color( Basin.color )\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def RenderShoals( self, init = False ):\n ''' '''\n\n for Shoal in self.model.Shoals.values():\n line_xy = Shoal.line_xy\n\n if line_xy is None :\n continue\n\n shoal_number = Shoal.name\n\n if init :\n Line2D_List = self.figure_axes.plot( line_xy[:,0], \n line_xy[:,1], \n #color, \n linewidth = 3,\n label = shoal_number,\n picker = True )\n\n Shoal.Axes_plot = Line2D_List[ 0 ]\n\n else :\n Shoal.Axes_plot.set_color( (1, 1, 1) )\n \n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def PlotLegend( self, label, init = True ) :\n ''' '''\n\n if self.model.args.DEBUG_ALL:\n print( '-> PlotLegend', flush = True )\n\n # Add an axes at position rect [left, bottom, width, height] \n # where all quantities are in fractions of figure width and height.\n # Just returns the existing axis if it already exists\n\n legendAxis = self.figure.add_axes( [ 0.05, 0.95, 0.7, 0.03 ],\n label = 'PlotLegend' + label )\n\n legend_color_map = ListedColormap( self.colors )\n\n #-----------------------------------------------------------\n # Set appropriate legend and data type for map plot\n plotVariable = self.mapPlotVariable.get()\n\n legend_bounds = None\n legend_label = None\n\n if plotVariable == 'Salinity' :\n legend_bounds = self.model.args.salinity_legend_bounds\n legend_label = 'Salinity (ppt)'\n\n elif plotVariable == 'Stage' : \n legend_bounds = self.model.args.stage_legend_bounds\n legend_label = 'Stage (m)'\n\n elif plotVariable == 'Temperature' or plotVariable == 'Phosphate' or \\\n plotVariable == 'Nitrate' or plotVariable == 'Ammonium' or \\\n plotVariable == 'Oxygen' or plotVariable == 'TOC' :\n \n msg = '\\nInvalid map legend variable selected, showing Stage.\\n'\n self.Message( msg )\n legend_label = 'Stage (m)'\n legend_bounds = self.model.args.stage_legend_bounds\n\n else :\n msg = '\\nError. Failed to find map legend type, showing Stage.\\n'\n self.Message( msg )\n legend_label = 'Stage (m)'\n legend_bounds = self.model.args.stage_legend_bounds\n #-----------------------------------------------------------\n\n norm = BoundaryNorm( legend_bounds, legend_color_map.N )\n\n if init :\n self.colorbar = ColorbarBase( \n legendAxis, \n cmap = legend_color_map,\n norm = norm,\n ticklocation = 'bottom',\n ticks = legend_bounds,\n #boundaries = legend_bounds,\n spacing = 'proportional', #'uniform',\n orientation = 'horizontal' )\n else:\n self.colorbar.set_norm( norm )\n self.colorbar.update_ticks( legend_bounds )\n \n self.colorbar.set_label( legend_label, size = 12 )\n self.colorbar.ax.tick_params( labelsize = 10 )\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def MouseClick( self, event ):\n '''For event.mouseevent see: \n http://matplotlib.org/api/backend_bases_api.html\n #matplotlib.backend_bases.MouseEvent'''\n\n if self.model.args.DEBUG_ALL:\n print( '-> MouseClick' )\n print( 'event.mouseevent: ', event.mouseevent )\n print( 'event.mouseevent.button: ', event.mouseevent.button )\n print( 'event.artist: ', event.artist )\n\n left_click = False\n middle_click = False\n right_click = False\n\n BasinObj = None\n\n if event.mouseevent.button == 1 :\n left_click = True\n elif event.mouseevent.button == 2 :\n middle_click = True\n elif event.mouseevent.button == 3 :\n right_click = True\n\n #--------------------------------------------------------\n # Left Click selects an object, either Basin or Shoal\n # and prints its info\n if left_click :\n\n # Shoals are instantiated as Line2D \n if isinstance( event.artist, Line2D ):\n line = event.artist\n\n # find the Shoal object\n for shoal_number, Shoal in self.model.Shoals.items() :\n if Shoal.Axes_plot == None :\n continue\n\n if Shoal.Axes_plot.get_label == line.get_label :\n\n Shoal.Print( shoal_number )\n break\n\n # Basins are instantiated as Polygon\n elif isinstance( event.artist, Polygon ):\n patch = event.artist\n\n # Find the Basin object\n Basin = None\n for Basin in self.model.Basins.values() :\n if Basin.Axes_fill == None :\n continue\n \n if Basin.Axes_fill.get_label() == patch.get_label() :\n Basin.Print()\n break\n\n # Select this basin in the basinListBox\n self.basinListBox.selection_clear( first = 1, \n last = max( self.basinListBoxMap.values() ) )\n\n self.basinListBox.selection_set( \n self.basinListBoxMap[ Basin.name ] )\n\n self.basinListBox.see( self.basinListBoxMap[ Basin.name ] )\n\n #--------------------------------------------------------\n # Middle Click selects a Basin and prints it's info\n elif middle_click :\n\n # Basins are instantiated as Polygon\n if isinstance( event.artist, Polygon ):\n patch = event.artist\n\n # Find the Basin object\n for Basin in self.model.Basins.values() :\n if Basin.Axes_fill == None :\n continue\n \n if Basin.Axes_fill.get_label() == patch.get_label() :\n Basin.Print()\n break\n\n #--------------------------------------------------------\n # Right Click selects a Basin and pops up its Shoal list\n # Selecting a listbox item prints the shoal information\n elif right_click :\n\n # Basins are instantiated as Polygon\n if isinstance( event.artist, Polygon ):\n patch = event.artist\n\n # Find the Basin object\n for Basin in self.model.Basins.values() :\n if Basin.Axes_fill == None :\n continue\n \n if Basin.Axes_fill.get_label() == patch.get_label() :\n\n BasinObj = Basin\n\n if self.model.args.DEBUG_ALL :\n print( '<<<< Basin Right Click:', \n Basin.name, ' Shoals:', Basin.shoal_nums,\n '>>>>', flush = True )\n break\n\n if BasinObj :\n # A top level pop up widget\n top = Tk.Toplevel()\n top.title( BasinObj.name + ' Shoals' ) \n\n # Shoal Listbox\n self.shoalListBox = Tk.Listbox( top, height = 11, width = 30, \n selectmode = Tk.EXTENDED,\n font = constants.textFont )\n\n # Insert shoal numbers into the Listbox\n # The listvariable = [] option won't work if\n # there is whitespace in a name, so insert them manually\n i = 1\n for shoal_number in BasinObj.shoal_nums :\n Basin_A_key = self.model.Shoals[ shoal_number ].Basin_A_key\n Basin_B_key = self.model.Shoals[ shoal_number ].Basin_B_key\n\n shoalInfo = str( shoal_number ) + ' ' +\\\n self.model.Basins[ Basin_A_key ].name + ' : ' +\\\n self.model.Basins[ Basin_B_key ].name\n \n self.shoalListBox.insert( i, shoalInfo )\n i = i + 1\n\n # Create a vertical scroll bar for the Listbox\n # Call the Listbox yview func when the user moves the scrollbar\n scrollBar = ttk.Scrollbar( top, orient = Tk.VERTICAL, \n command = self.shoalListBox.yview )\n\n # Tell the Listbox it will scroll according to the scrollBar\n self.shoalListBox.configure( yscrollcommand = scrollBar.set )\n\n # Colorize alternating lines of the listbox\n for i in range( 0, len( BasinObj.shoal_nums ), 2):\n self.shoalListBox.itemconfigure( i, background = '#f0f0ff' )\n\n # Can use pack here since this is a standalone widget that\n # doesn't interact with a grid geometry\n scrollBar.pack( side = Tk.LEFT, expand = True, fill = Tk.Y )\n self.shoalListBox.pack( side = Tk.RIGHT, expand = True, \n fill = Tk.BOTH )\n\n # Tell Listbox to call ProcessShoalListbox()\n self.shoalListBox.bind( '<>', \n self.ProcessShoalListbox )\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def ProcessShoalListbox( self, *args ):\n '''Read the Shoal listbox selection, Print the Shoal info.'''\n # \\n separated items in one string\n selected = self.shoalListBox.selection_get()\n\n shoal_list = selected.split( '\\n' ) # A list of strings\n\n if self.model.args.DEBUG_ALL:\n print( '-> ProcessShoalListbox() ', len( shoal_list ), '\\n',\n shoal_list, flush = True )\n\n # Find the Shoal objects and store in Shoal_list\n Shoal_list = []\n for shoal_info in shoal_list :\n words = shoal_info.split()\n shoal_number = int( words[ 0 ] )\n Shoal = self.model.Shoals[ shoal_number ]\n Shoal_list.append( Shoal )\n Shoal.Print( shoal_number )\n\n # return Shoal_list\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def ProcessBasinListbox( self, *args ):\n '''Print the Basin listbox selections'''\n Basin_list = self.GetBasinListbox()\n \n for Basin in Basin_list :\n Basin.Print()\n\n #----------------------------------------------------------------\n # \n #----------------------------------------------------------------\n def GetBasinListbox( self ):\n '''Read the Basin listbox selection.\n Return a list of Basin objects.'''\n\n # Get the names of selected basins\n # \\n separated items in one string\n try :\n selected = self.basinListBox.selection_get()\n except Tk._tkinter.TclError :\n # Nothing is selected\n return []\n\n basin_name_list = selected.split( '\\n' ) # A list of strings\n\n if self.model.args.DEBUG_ALL :\n print( '-> GetBasinListbox() ', len( basin_name_list ), '\\n',\n basin_name_list, flush = True )\n\n # Find the Basin objects and store in Basin_list\n Basin_list = []\n for basin_name in basin_name_list :\n for Basin in self.model.Basins.values() :\n # Since the Basins keys are basin numbers, match the names\n if Basin.name == basin_name :\n Basin_list.append( Basin )\n\n return Basin_list\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def ShowAboutInfo( self ):\n messagebox.showinfo( message = self.model.Version )\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def OpenInitFile( self ):\n '''Open a basin initialization file and call InitTimeBasin.'''\n if self.model.args.DEBUG_ALL :\n print( '-> OpenInitFile(): ', flush = True ) \n\n input_file = filedialog.askopenfilename(\n initialdir = self.model.args.path + 'data/init/',\n initialfile = 'Basin_Initial_Values.csv', \n filetypes = [('Basin Init Files', '*.csv')],\n multiple = False,\n title = 'Basin Initialization File' )\n\n if not input_file :\n return\n\n # Since we store the path and files seperately, but input_file\n # contains the whole path, strip off the model base path.\n # Since askopenfilename returns the entire path that may not\n # have the same prefix specified in args.path (since args.path\n # may be referring to a symbolic link), strip off everything\n # prior to data/init : this is stupid since it now requires\n # this file to reside in data/init... \n input_file = input_file[ input_file.rfind( 'data/init/' ) : ]\n \n self.model.args.basinInit = input_file\n\n InitTimeBasins( self.model )\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def EditFile( self ):\n '''Edit a file with the current editor.'''\n if self.model.args.DEBUG_ALL:\n print( '-> EditFile(): ', flush = True ) \n\n edit_file = filedialog.askopenfilename(\n initialdir = self.model.args.path,\n # initialfile = '', \n filetypes = [ ('Data', '*.csv'), \n ('Source', '*.py' ),\n ('R', '*.R' ),\n ('All', '*' ) ],\n multiple = False )\n\n if not edit_file :\n return\n\n cmdLine = self.model.args.editor + ' ' + edit_file.replace(' ', '\\ ')\n\n try :\n sp = Popen( cmdLine, shell = True )\n except OSError as err:\n msg = \"\\nEditFile: OS error: {0}\\n\".format( err )\n self.Message( msg )\n except ValueError as err:\n msg = \"\\nEditFile: Value error: {0}\\n\".format( err )\n self.Message( msg )\n except:\n errMsg = \"\\nEditFile Error:\" + sys.exc_info()[0] + '\\n.'\n self.Message( msg )\n raise Exception( errMsg )\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def GetPlotDir( self ):\n '''Set the directory for disk/archive plots.'''\n if self.model.args.DEBUG_ALL :\n print( '-> (): GetPlotDir', flush = True ) \n\n # Tk.filedialog.askdirectory clears the listbox selection, save it\n BasinList = self.GetBasinListbox()\n\n if path_exists( self.last_plot_dir ) :\n initial_plot_dir = self.last_plot_dir\n else :\n initial_plot_dir = self.model.args.homeDir\n\n # Get the file path and runid\n archive_dir = filedialog.askdirectory(\n initialdir = initial_plot_dir,\n title = 'Plot Archive Directory',\n mustexist = True )\n\n # Reset the listbox selection\n for Basin in BasinList :\n self.basinListBox.selection_set(self.basinListBoxMap[ Basin.name ])\n\n if not archive_dir :\n return\n\n self.plot_dir = archive_dir\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def GetOutputDir( self ):\n '''Set the directory for basin output files.'''\n if self.model.args.DEBUG_ALL :\n print( '-> (): GetOutputDir', flush = True ) \n\n # Tk.filedialog.askdirectory clears the listbox selection, save it\n BasinList = self.GetBasinListbox()\n\n if path_exists( self.model.args.basinOutputDir ) :\n initial_out_dir = self.model.args.basinOutputDir\n else :\n initial_out_dir = self.model.args.homeDir\n\n # Get the file path and runid\n output_dir = filedialog.askdirectory(\n initialdir = initial_out_dir,\n title = 'Basin Output Directory',\n mustexist = False )\n\n # Reset the listbox selection\n for Basin in BasinList :\n self.basinListBox.selection_set(self.basinListBoxMap[ Basin.name ])\n\n if not output_dir :\n return\n\n self.model.args.basinOutputDir = output_dir\n\n self.Message( 'Set basin output directory to: ' +\\\n self.model.args.basinOutputDir + '\\n' )\n\n #-----------------------------------------------------------\n #\n #-----------------------------------------------------------\n def CheckTimeEntry( self, newTime, widgetName ):\n '''Validate the time entry for an update to start_time or end_time.\n Times must be on hour boundaries (zero minutes) since the tidal\n data is aligned on the hour.'''\n\n if self.model.args.DEBUG_ALL :\n print( '-> CheckTimeEntry(): ', newTime, flush = True ) \n\n try :\n if ':' in newTime :\n format_string = '%Y-%m-%d %H:%M'\n else :\n format_string = '%Y-%m-%d'\n\n time = datetime.strptime( newTime, format_string )\n\n except ValueError :\n # Reset text to original values, return False\n if widgetName == str( self.startTimeEntry ) :\n start_text = \\\n str( self.model.start_time.strftime( '%Y-%m-%d %H:%M' ) )\n self.start_text.set( start_text )\n\n elif widgetName == str( self.endTimeEntry ) :\n end_text = str(self.model.end_time.strftime( '%Y-%m-%d %H:%M' ))\n self.end_text.set( end_text )\n\n return False\n\n # Align the time to an hour boundary\n time = time - timedelta(minutes = time.minute, seconds = time.second)\n\n # Save both initial times so comparison in InitTimeBasins is valid\n self.model.previous_start_time = self.model.start_time\n self.model.previous_end_time = self.model.end_time\n\n if widgetName == str( self.startTimeEntry ) :\n start_text = str( time.strftime( '%Y-%m-%d %H:%M' ) )\n self.start_text.set( start_text )\n self.model.start_time = time\n\n elif widgetName == str( self.endTimeEntry ) :\n end_text = str( time.strftime( '%Y-%m-%d %H:%M' ) )\n self.end_text.set( end_text )\n self.model.end_time = time\n\n InitTimeBasins( self.model )\n\n if self.model.args.DEBUG_ALL :\n print( ' New time: ', str( time ), flush = True ) \n\n return True\n\n#---------------------------------------------------------------\n# \n#---------------------------------------------------------------\nclass IntVar :\n '''Surrogate for Tk.IntVar() when non-GUI option invoked.\n Provides set() and get() methods.'''\n\n def __init__( self, value = 0 ):\n self.value = value\n\n def set( self, value ) :\n self.value = value\n\n def get( self ) :\n return self.value\n","repo_name":"SoftwareLiteracyFoundation/BAM","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":60575,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"35474191648","text":"import serial\nimport time\n\n\nclass Braille():\n def __init__(self,COM): #initialises the braille printer, use COM as serial port\n self.xstep = 2.5\n self.zstep = 10\n self.xmin = 20\n self.xsize = 150\n self.speed = 1000\n self.x = 0\n self.y = 0\n self.z = 30\n self.ser = serial.Serial(COM, '250000', timeout=2)\n\n def init_printer(self):\n self.readall()\n self.write('G28') # home all\n self.x = 0;\n self.y = 0;\n self.z = 0;\n self.write('M211 Z1 S0') # disable the z endStop\n self.move()\n\n def open_serial(self):\n if (not self.ser.is_open) :\n self.ser.open()\n \n def close_serial(self):\n if (self.ser.is_open) :\n self.ser.close()\n \n def servo(self,number): # move servo to position 0-7\n self.write('M400')\n self.write('M280 P0 S' + str(self.servo_number(number)))\n\n def servo_number(self,number): # Calibration of the servo position from 0-7 to degres\n return {\n 0: 0,\n 1: 80,\n 2: 40,\n 3: 125,\n 4: 20,\n 5: 105,\n 6: 60,\n 7: 150,\n }[number]\n\n def letters(self,letter):\t\t\t\t\t#Transforms the letters into numbers for the encoder\n return{\n 'a' : [1,0],\n 'b' : [3,0],\n 'c' : [1,1],\n 'd' : [1,3],\n 'e' : [1,2],\n 'f' : [3,1],\n 'g' : [3,3],\n 'h' : [3,2],\n 'i' : [2,1],\n 'j' : [2,3],\n 'k' : [5,0],\n 'l' : [7,0],\n 'm' : [5,1],\n 'n' : [5,3],\n 'o' : [5,2],\n 'p' : [7,1],\n 'q' : [7,3],\n 'r' : [7,2],\n 's' : [6,1],\n 't' : [6,3],\n 'u' : [5,4],\n 'v' : [7,4],\n 'x' : [5,5],\n 'y' : [5,7],\n 'z' : [5,6],\n ' ' : [0,0],\n }.get(letter, [7, 7])\n x = 0\n\n def write(self,line): ## Serial write to the arduino\n print(line)\n self.ser.write((line+' \\n').encode())\n response = ' : ' + self.ser.readline().decode()\n print(response)\n while response.find('unknown') != -1:\n self.ser.write((line + ' \\n').encode())\n response = ' : ' + self.ser.readline().decode()\n print(\"reprinting line : \" + line)\n while response.find('busy') != -1:\n time.sleep(1)\n response = ' : ' + self.ser.readline().decode()\n print(response)\n\n\n\n\n def move(self):\t\t\t\t\t\t\n self.write('G1' + ' X' + str(self.x) + ' Y' + str(self.y) + ' Z' + str(self.z) + ' F' + str(self.speed))\n #print('G0' + ' X' + str(self.x) + ' Y' + str(self.y) + ' Z' + str(self.z))\n\n def eject_paper(self):\n self.x = self.x - 30\n self.move()\n self.z = self.z + 50\n self.move()\n\n def emboss(self,digits):\t\t\t\t\t\t\t#routine for embossing letters\n if self.x < self.xmin:\n self.y = self.xmin\n self.move()\n self.x = self.xmin - 2*self.xstep\n self.move()\n if self.x > self.xsize:\n self.x = self.x - 3*self.xstep\n self.x = self.xmin - 3*self.xstep\n self.y = self.xmin\n self.move()\n self.z = self.z + self.zstep\n self.move()\n for digit in digits:\n if digit==0:\n self.x = self.x + self.xstep\n self.y = self.y + self.xstep\n self.move()\n else:\n self.servo(digit)\n self.y = self.y + self.xstep\n self.move()\n self.x = self.y + 2*self.xstep\n self.move()\n self.x = self.y - 3*self.xstep\n self.move()\n self.x = self.x + self.xstep\n self.y = self.y + self.xstep\n self.move()\n\n def readall(self):\t\t\t\t\t\t\t\t\t\t#Clears the buffer\n self.ser.readline()\n while self.ser.in_waiting != 0:\n print(self.ser.readline().decode(\"utf-8\"))\n\n\n# abcdefghijklmnopqrstuvxyz\n\n\n\n","repo_name":"carloscamposalcocer/OpenBraille","sub_path":"writer/braille.py","file_name":"braille.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"80"} +{"seq_id":"29119254946","text":"import os\nfrom ctypes import c_int, c_float\nimport numpy as np\nfrom numpy import ctypeslib as ctl\nfrom mmdet.datasets.builder import PIPELINES\n\n\n@PIPELINES.register_module()\nclass GPMADataGeneration:\n \"\"\" Generate gt_mask for training(GPMA branch).\n\n Ref: Qiao L, Li Z, Cheng Z, et al. LGPMA: Complicated Table Structure Recognition with Local and Global Pyramid Mask\n Alignment[J]. arXiv preprint arXiv:2105.06224, 2021. (Accepted by ICDAR 2021, Best Industry Paper)\n\n \"\"\"\n\n def __init__(self,\n ignore_ratio=0.6,\n shrink_ratio=(0, 1 / 10),\n lib_name=None,\n lib_dir=None\n ):\n \"\"\"Generate gt_mask for training(GPMA branch)\n\n Args:\n ignore_ratio (float): Controls the ratio of background pixels to foreground pixels\n shrink_ratio (tuple): Controls the ratio of shrink (ensure that virtual or real table lines are preserved)\n lib_name (str): lib name of calling the function of ground-truth label generation\n lib_dir (str): lib path to calling the function of ground-truth label generation\n \"\"\"\n\n if lib_name is None or not os.path.isfile(os.path.join(lib_dir, lib_name)):\n # Using default lib\n cur_path = os.path.realpath(__file__)\n lib_dir = cur_path.replace('\\\\', '/').split('/')[:-1]\n lib_dir = \"/\".join(lib_dir) + '/lib'\n lib_name = \"gpma_data.so\"\n if lib_name is not None and lib_dir is not None:\n lib = ctl.load_library(lib_name, lib_dir)\n self.generate_func = lib.generate_seg_data\n self.generate_func.argtypes = [\n c_int, # height\n c_int, # width\n ctl.ndpointer(np.float32, ndim=2, flags='C_CONTIGUOUS'), # gt_boxes\n c_int, # gt_boxes_size\n ctl.ndpointer(np.float32, ndim=2, flags='C_CONTIGUOUS'), # shrink_gt_boxes\n c_int, # empty_gt_boxes_size\n ctl.ndpointer(np.float32, ndim=2, flags='C_CONTIGUOUS'), # empty_gt_boxes\n c_int, # empty_gt_boxes_size\n ctl.ndpointer(np.float32, ndim=2, flags='C_CONTIGUOUS'), # small_gt_boxes\n c_int, # small_gt_boxes_size\n c_int, # pool_ratio,\n c_float, # ignore_ratio\n ctl.ndpointer(np.int32, flags='C_CONTIGUOUS'), # gt_score_map\n ctl.ndpointer(np.int32, flags='C_CONTIGUOUS'), # gt_mask\n ctl.ndpointer(np.float32, flags='C_CONTIGUOUS'), # gt_geo_data\n ctl.ndpointer(np.float32, flags='C_CONTIGUOUS'), # gt_geo_weight\n ]\n else:\n self.generate_func = None\n self.ignore_ratio = ignore_ratio\n self.shrink_ratio = shrink_ratio\n\n def __call__(self, results):\n \"\"\"Data generation pipeline\n\n Args:\n results(dict): Data flow, requires\n results['pad_shape'], image shape after padding tupe(3, H, W)\n results['gt_bboxes'], ground-truth bboxes of non-empty aligned cells [[x1, y1, x2, y2], ...]\n results['gt_content_bboxes'], ground-truth bboxes of text regions [[x1, y2, x2, y2],...[...]]\n results['gt_empty_bboxes'],ground-truth bboxes of empty aligned cells [[x1, y1, x2, y2], ...]\n\n Returns:\n results(dict): Data flow, updated results['gt_semantic_seg]: np.ndarray(N, 6, H, W], where N is batch size\n gt_semantic_seg:[:,0]: gt_cell_region\n gt_semantic_seg:[:,1]: cell_region_weight, 1 Care / 0 Not Care\n gt_semantic_seg:[:,2:4]: gt_global_pyramid\n gt_semantic_seg:[:,4:6]: global_pyramid_weight, 1 Care / 0 Not Care\n\n \"\"\"\n\n if 'gt_labels' not in results:\n results['gt_labels'] = [1] * len(results['gt_bboxes'])\n # shrinked bboxes of empty cells\n gt_empty_bboxes = []\n for bbox in results.get(\"gt_empty_bboxes\", []):\n xoffset, yoffset = (bbox[2] - bbox[0]) * self.shrink_ratio[0], (bbox[3] - bbox[1]) * self.shrink_ratio[1]\n temp = [bbox[0] + xoffset, bbox[1] + yoffset, bbox[2] - xoffset, bbox[3] - yoffset]\n gt_empty_bboxes.append(temp)\n\n gt_semantic_seg = self._parse_gpma_data_cpp(results['pad_shape'], results['gt_bboxes'],\n results['gt_content_bboxes'], gt_empty_bboxes)\n\n results['gt_semantic_seg'] = gt_semantic_seg\n\n return results\n\n def _parse_gpma_data_cpp(self, img_shape, gt_cell_bboxes, gt_content_bboxes, gt_empty_bboxes, pool_ratio=4):\n \"\"\"Parsing and generating gt_mask for training(GPMA branch), by calling C++ lib\n\n Args:\n img_shape(Tuple): image size (pad_shape)\n gt_cell_bboxes(list[list[float]]): ground-truth bboxes of non-empty aligned cells [[x1, y1, x2, y2], ...]\n gt_content_bboxes(list[list[float]]): ground-truth bboxes of text regions [[x1, y2, x2, y2],...[...]]\n gt_empty_bboxes(list[list[float]]): ground-truth bboxes of empty aligned cells [[x1, y1, x2, y2], ...]\n pool_ratio(int): downsampling ratio of ground-truth map wrt original image\n\n Returns:\n np.array: All gts in a np.array, including\n gt_cell_region: target aligned cell region mask ground-truth [H x W]\n cell_region_weight: weight mask of target aligned cell region (ignored if 0) [H x W]\n gt_global_pyramid: target global pyramid mask ground-truth [2 x H x W]\n global_pyramid_weight: weight mask of target global pyramid mask (ignored if 0) [2 x H x W]\n \"\"\"\n\n gt_shrink_bboxes = []\n for bbox in gt_cell_bboxes:\n xoffset, yoffset = (bbox[2] - bbox[0]) * self.shrink_ratio[0], (bbox[3] - bbox[1]) * self.shrink_ratio[1]\n temp = [bbox[0] + xoffset, bbox[1] + yoffset, bbox[2] - xoffset, bbox[3] - yoffset]\n gt_shrink_bboxes.append(temp)\n assert len(gt_cell_bboxes) == len(gt_content_bboxes) == len(gt_shrink_bboxes)\n\n gt_cell_bboxes = np.array([[box[0], box[1], box[2], box[3]] for box in gt_cell_bboxes], dtype=np.float32)\n gt_shrink_bboxes = np.array([[box[0], box[1], box[2], box[3]] for box in gt_shrink_bboxes], dtype=np.float32)\n gt_content_bboxes = np.array([[box[0], box[1], box[2], box[3]] for box in gt_content_bboxes], dtype=np.float32)\n if len(gt_empty_bboxes) == 0:\n gt_empty_bboxes = np.zeros((0, 4), dtype=np.float32)\n else:\n gt_empty_bboxes = np.array([[box[0], box[1], box[2], box[3]] for box in gt_empty_bboxes], dtype=np.float32)\n\n height, width, _ = img_shape\n new_height = int(height / pool_ratio)\n new_width = int(width / pool_ratio)\n\n # Used to store output results.\n gt_cell_region = np.zeros(new_height * new_width, dtype=np.int32)\n cell_region_weight = np.ones(new_height * new_width, dtype=np.int32)\n gt_global_pyramid = np.zeros(2 * new_height * new_width, dtype=np.float32)\n global_pyramid_weight = np.zeros(2 * new_height * new_width, dtype=np.float32)\n\n # Call C++ lib execution\n self.generate_func(height, width, gt_cell_bboxes, len(gt_cell_bboxes), gt_shrink_bboxes, len(gt_shrink_bboxes),\n gt_empty_bboxes, len(gt_empty_bboxes),\n gt_content_bboxes, len(gt_content_bboxes),\n pool_ratio, self.ignore_ratio, gt_cell_region, cell_region_weight,\n gt_global_pyramid, global_pyramid_weight)\n\n # Return the formatted results\n gt_cell_region = np.array(gt_cell_region.reshape(new_height, new_width), dtype=np.int32)\n cell_region_weight = np.array(cell_region_weight.reshape(new_height, new_width), dtype=np.int32)\n gt_global_pyramid = np.array(gt_global_pyramid.reshape((2, new_height, new_width)), dtype=np.float32)\n global_pyramid_weight = np.array(global_pyramid_weight.reshape((2, new_height, new_width)), dtype=np.float32)\n\n return np.concatenate([gt_cell_region[np.newaxis, :, :], cell_region_weight[np.newaxis, :, :],\n gt_global_pyramid, global_pyramid_weight], axis=0)\n","repo_name":"hikopensource/DAVAR-Lab-OCR","sub_path":"davarocr/davar_table/datasets/pipelines/gpma_data.py","file_name":"gpma_data.py","file_ext":"py","file_size_in_byte":8447,"program_lang":"python","lang":"en","doc_type":"code","stars":677,"dataset":"github-code","pt":"80"} +{"seq_id":"35938558277","text":"\"\"\"Example script to check how good the model\ncan approximate solutions with different thermal conductivity D\n\"\"\"\nimport os\nimport json\n\nimport torch\nimport numpy as np\nimport pytorch_lightning as pl\nfrom timeit import default_timer as timer\n\nfrom torchphysics.problem import (Variable,\n Setting)\nfrom torchphysics.problem.domain import (Rectangle,\n Interval)\nfrom torchphysics.problem.condition import (DirichletCondition,\n DiffEqCondition,\n DataCondition)\nfrom torchphysics.models import SimpleFCN\nfrom torchphysics import PINNModule\nfrom torchphysics.utils import laplacian, grad\nfrom torchphysics.utils.fdm import FDM, create_validation_data\nfrom torchphysics.utils.plot import Plotter\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n\n#pl.seed_everything(43)\n\nw, h = 50, 50\nt0, tend = 0, 1\ntemp_hot = 10\nD_low, D_up = 5, 25 # set here the interval boundary for D\n\nx = Variable(name='x',\n order=2,\n domain=Rectangle(corner_dl=[0, 0],\n corner_dr=[w, 0],\n corner_tl=[0, h]),\n train_conditions={},\n val_conditions={})\nt = Variable(name='t',\n order=1,\n domain=Interval(low_bound=0,\n up_bound=tend),\n train_conditions={},\n val_conditions={})\nD = Variable(name='D',\n order=0,\n domain=Interval(low_bound=D_low,\n up_bound=D_up),\n train_conditions={},\n val_conditions={})\n\n\ndef x_dirichlet_fun(input):\n return torch.zeros_like(input['t'])\n\n\nnorm = torch.nn.MSELoss()\n\n\nx.add_train_condition(DirichletCondition(dirichlet_fun=x_dirichlet_fun,\n name='dirichlet',\n norm=norm,\n batch_size=500,\n dataset_size=500,\n num_workers=4,\n data_plot_variables=('x','t')))\n\n\ndef t_dirichlet_fun(input):\n return temp_hot*torch.sin(np.pi/w*input['x'][:, :1])*torch.sin(np.pi/h*input['x'][:, 1:])\n\n\nt.add_train_condition(DirichletCondition(dirichlet_fun=t_dirichlet_fun,\n name='dirichlet',\n norm=norm,\n batch_size=500,\n dataset_size=500,\n num_workers=4,\n boundary_sampling_strategy='lower_bound_only',\n data_plot_variables=('x','t')))\n\n\ndef pde(u, input):\n return grad(u, input['t']) - input['D']*laplacian(u, input['x'])\n\n\ntrain_cond = DiffEqCondition(pde=pde,\n norm=norm,\n batch_size=5000,\n dataset_size=5000,\n num_workers=8,\n data_plot_variables=('x','t'))\n\n# FDM:\ndomain_dic = {'x': [[0, w], [0, h]]}\ndx, dy = 0.5, 0.5\nstep_width_dict = {'x': [dx, dy]}\ntime_interval = [t0, tend]\n\n\ndef inital_condition(input):\n return temp_hot * np.sin(np.pi/w*input['x'][:, :1]) * np.sin(np.pi/h*input['x'][:, 1:])\n\n\nD_list = [5, 10, 15, 20, 25]\n# ^Here you can add many different values for D, e.g [18.8,2.5,20,....]\n# The FDM-Methode will compute solutions for all D.\n# For too many D this will become really memory expensive, since\n# the FDM uses a forward euler!\nfdm_start = timer()\ndomain, time, u = FDM(domain_dic, step_width_dict, time_interval,\n D_list, inital_condition)\nfdm_end = timer()\nprint('Time for FDM-Solution:', fdm_end-fdm_start)\ndata_x, data_u = create_validation_data(domain, time, u, D_list, D_is_input=True)\n# True: if D is input of the model\n\n\nclass InfNorm(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, input_a, input_b):\n return torch.max(torch.abs(input_a-input_b))\n\n\nmax_norm = InfNorm()\n\nval_cond = DataCondition(data_x=data_x,\n data_u=data_u,\n name='validation',\n norm=norm,\n batch_size=len(data_u[:, 0])//100,\n num_workers=16)\n\nsetup = Setting(variables=(x, t, D),\n train_conditions={'pde': train_cond},\n val_conditions={'validation': val_cond})\n\nplotter = Plotter(plot_variables=setup.variables['x'],\n points=400,\n dic_for_other_variables={'t': 1.0, 'D': 15.0},\n all_variables=setup.variables,\n log_interval=10)\n\nsolver = PINNModule(model=SimpleFCN(input_dim=4), # TODO: comput input_dim in setting\n problem=setup,\n #optimizer=torch.optim.Adam,\n #lr=1e-3,\n #log_plotter=plotter\n )\n\n#print(json.dumps(solver.serialize(), indent=2))\n\ntrainer = pl.Trainer(gpus=None,#'-1',\n #accelerator='ddp',\n #plugins=pl.plugins.DDPPlugin(find_unused_parameters=False),\n num_sanity_val_steps=2,\n check_val_every_n_epoch=100,\n log_every_n_steps=1,\n max_epochs=10000,\n # limit_val_batches=10, # The validation dataset is probably pretty big,\n # so you need to see how much you want to\n # check every validation\n # checkpoint_callback=False)\n )\n\ntrainer.fit(solver)\n","repo_name":"AsclepiusInformatica/torchphysics","sub_path":"experiments/heat_equation/heat_equation_D_variable.py","file_name":"heat_equation_D_variable.py","file_ext":"py","file_size_in_byte":5842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"80"} +{"seq_id":"75073918019","text":"# User configuration file typically located at `~/.config/nerd-dictation/nerd-dictation.py`\nimport re\n\n# Usage:\n\n# [] [] [space,ha]\n# [] \n\n# [] : Chain any number of single commands\n# [] : Modify prose (caps, snake, camel...)\n# : Dictate any textual phrase\n# : Multi-word command, cannot be chained\n# [space,ha] : Finish input with space or enter key\n\n# Emacs Commands that are dictated one to one\nEMACS_COMMANDS = [\n \"find file\",\n \"switch buffer\",\n \"query replace\",\n \"newline anywhere\",\n \"learn replacement\",\n \"bookmark jump\",\n \"bookmark set\",\n \"learn emacs command\",\n \"scroll up\",\n \"scroll down\",\n \"kill line\",\n \"other window\",\n \"other buffer\",\n \"save buffer\",\n]\n\n# Replace Multiple Words\n\nTEXT_REPLACE_REGEX = (\n (\"\\\\b\" \"and of\" \"\\\\b\", \"end of\"),\n (\"\\\\b\" \"se[ae] [ae]nd\" \"\\\\b\", \"&&\"),\n (\"\\\\b\" \"c [ae]nd\" \"\\\\b\", \"&&\"),\n (\"\\\\b\" \"se[ae] equal.?\" \"\\\\b\", \"==\"),\n (\"\\\\b\" \"c equal.?\" \"\\\\b\", \"==\"),\n (\"\\\\b\" \"se[ae] not\" \"\\\\b\", \"!=\"),\n (\"\\\\b\" \"[kg][ae]t [hae]nd\" \"\\\\b\", \"git add\"),\n (\"\\\\b\" \"key word\" \"\\\\b\", \"keyword\"),\n (\"\\\\b\" \"for each\" \"\\\\b\", \"foreach\"),\n (\"\\\\b\" \"new line\" \"\\\\b\", \"newline\"),\n (\"\\\\b\" \"right boy\" \"\\\\b\", \")\"),\n (\"\\\\b\" \"[ea]nd boy\" \"\\\\b\", \")\"),\n (\"\\\\b\" \"right bracket\" \"\\\\b\", \"]\"),\n (\"\\\\b\" \"right curly\" \"\\\\b\", \"}\"),\n (\"\\\\b\" \"x ray\" \"\\\\b\", \"x\"),\n (\"\\\\b\" \"exclamation point\" \"\\\\b\", \"!\"),\n (\"\\\\b\" \"question mark\" \"\\\\b\", \"?\"),\n (\"\\\\b\" \"less than\" \"\\\\b\", \"<\"),\n (\"\\\\b\" \"greater than\" \"\\\\b\", \">\"),\n (\"\\\\b\" \"d fun\" \"\\\\b\", \"defun\"),\n)\nTEXT_REPLACE_REGEX = tuple(\n (re.compile(match), replacement)\n for (match, replacement) in TEXT_REPLACE_REGEX\n)\n\n# Replace Single Words\n\nWORD_REPLACE = {\n \"kit\":\"git\",\n \"arx\":\"args\",\n \"arcs\":\"args\",\n \"da\":\".\",\n \"dont\":\".\",\n \"kama\":\",\",\n \"cancer\":\"cancel\",\n \"get\": \"git\",\n \"the\": \"\", # HACK\n \"huh\": \"\", # HACK\n \"h\": \"\", # HACK\n \"hi\": \"\", # HACK\n \"diary\": \"dired\",\n \"deuce\": \"2\",\n \"quad\": \"4\",\n \"quand\": \"4\",\n \"define\": \"defun\",\n\n # symbols\n \"dash\": \"-\",\n \"quotes\": \"\\\"\",\n \"boy\": \"(\",\n \"bracket\": \"[\",\n \"curly\": \"{\",\n \"slash\": \"/\",\n \"colon\": \":\",\n \"colin\": \":\",\n \"coin\": \":\",\n \"cohen\": \":\",\n \"apostrophe\": \"'\",\n \"comma\": \",\",\n \"come\": \",\",\n \"coma\": \",\",\n \"karma\": \",\",\n \"semi\": \";\",\n \"dot\": \".\",\n \"spot\": \".\",\n \"don\": \".\",\n \"tilda\": \"~\",\n \"tick\": \"`\",\n \"equals\": \"=\",\n \"sequal\": \"==\",\n \"sequals\": \"==\",\n \"sequel\": \"==\",\n \"sequels\": \"==\",\n \"asterisk\": \"*\",\n \"carrot\": \"^\",\n # \"amp\": \"&\",\n \"sand\": \"&&\",\n \"cn\": \"&&\",\n \"cnn\": \"&&\",\n \"san\": \"&&\",\n \"pipe\": \"|\",\n \"cr\": \"||\",\n \"at\": \"@\",\n \"hash\": \"#\",\n \"percent\": \"%\",\n \"underscore\": \"_\",\n \"backslash\": \"\\\\\",\n\n # nato phonetic\n \"alpha\": \"a\",\n \"bravo\": \"b\",\n \"charlie\": \"c\",\n \"delta\": \"d\",\n \"echo\": \"e\",\n \"foxtrot\": \"f\",\n \"golf\": \"g\",\n \"gulf\": \"g\",\n \"hotel\": \"h\",\n \"india\": \"i\",\n \"juliet\": \"j\",\n \"kilos\": \"k\",\n \"kilo\": \"k\",\n \"lima\": \"l\",\n \"mike\": \"m\",\n \"november\": \"n\",\n \"oscar\": \"o\",\n \"papa\": \"p\",\n \"quebec\": \"q\",\n \"romeo\": \"r\",\n \"sierra\": \"s\",\n \"tango\": \"t\",\n \"uniform\": \"u\",\n \"victor\": \"v\",\n \"whiskey\": \"w\",\n \"yankee\": \"y\",\n \"zulu\": \"z\",\n}\n\n# Regular expressions allow partial words to be replaced.\nWORD_REPLACE_REGEX = (\n (\"^i'(.*)\", \"I'\\\\1\"),\n)\nWORD_REPLACE_REGEX = tuple(\n (re.compile(match), replacement)\n for (match, replacement) in WORD_REPLACE_REGEX\n)\n\n\n# Main Processing Function\n\ndef pressKey(key):\n return (\n \"xdotool\",\n \"key\",\n key,\n )\n\ndef typeText(text):\n return (\n \"xdotool\",\n \"type\",\n \"--clearmodifiers\",\n \"--delay\",\n \"10\",\n \"--\",\n text,\n )\n\ndef emacs_command(text):\n return [\n pressKey(\"alt+x\"),\n typeText(text),\n pressKey(\"enter\"),\n ]\n\ndef process_single_word_macro(macro):\n if (macro == \"expand\" or macro == \"enhance\"):\n return emacs_command(\"er/expand-region\")\n if (macro == \"snap\"):\n return emacs_command(\"sp-beginning-of-sexp\")\n if (macro == \"beginning\"):\n return [pressKey(\"control+a\")]\n if (macro == \"tip\"):\n return [pressKey(\"control+e\")]\n if (macro == \"next\"):\n return [pressKey(\"control+n\")]\n if (macro == \"previous\"):\n return [pressKey(\"control+p\")]\n if (macro == \"quit\" or macro == \"exit\"):\n return [\n pressKey(\"control+g\"),\n pressKey(\"control+g\"),\n pressKey(\"control+g\"),\n ]\n if (macro == \"leader\"):\n return [pressKey(\"control+c\")]\n if (macro == \"execute\"):\n return [pressKey(\"control+c\"),\n pressKey(\"control+c\")]\n if (macro == \"cancel\"):\n return [pressKey(\"control+g\")]\n if (macro == \"haha\"):\n return [pressKey(\"enter\"), pressKey(\"enter\")]\n if (macro == \"ha\"):\n return [pressKey(\"enter\")]\n if (macro == \"space\"):\n return [typeText(\" \")]\n if (macro == \"copy\"):\n return emacs_command(\"kill-ring-save\")\n if (macro == \"paste\"):\n return emacs_command(\"yank\")\n if (macro == \"cut\"):\n return emacs_command(\"cua-cut-region\")\n if (macro == \"undo\" or macro == \"fuck\"):\n return emacs_command(\"undo\")\n if (macro == \"toss\" or macro == \"tass\" or macro == \"tas\" or macro == \"taas\"):\n return emacs_command(\"revert-buffer-no-confirm\")\n if (macro == \"replace\"):\n return emacs_command(\"query-replace\")\n if (macro == \"flop\"):\n return emacs_command(\"beginning-of-buffer\")\n if (macro == \"river\"):\n return emacs_command(\"end-of-buffer\")\n if (macro == \"save\" or macro == \"safe\"):\n return emacs_command(\"save-buffer\")\n if (macro == \"duplicate\"):\n return emacs_command(\"duplicate-region\")\n if (macro == \"punch\"):\n return emacs_command(\"kill-word\")\n if (macro == \"kill\"):\n return emacs_command(\"kill-line\")\n if (macro == \"chomp\" or macro == \"champ\" or macro == \"chump\"):\n return [pressKey(\"alt+f\")]\n if (macro == \"poop\"):\n return [pressKey(\"alt+b\")]\n if (macro == \"slap\" or macro == \"slam\"):\n return [pressKey(\"alt+BackSpace\")]\n if (macro == \"backpack\"):\n return [pressKey(\"alt+BackSpace\"),\n pressKey(\"alt+BackSpace\")]\n if (macro == \"back\"):\n return [pressKey(\"BackSpace\")]\n if (macro == \"backward\" or macro == \"backwards\"):\n return [pressKey(\"control+b\")]\n if (macro == \"forward\" or macro == \"foreign\"):\n return [pressKey(\"control+f\")]\n if (macro == \"com\" or macro == \"calm\" or macro == \"command\"):\n return [pressKey(\"alt+x\")]\n if (macro == \"tab\" or macro == \"indent\"):\n return [pressKey(\"Tab\")]\n if (macro == \"search\"):\n return [pressKey(\"control+s\")]\n if (macro == \"reverse\"):\n return [pressKey(\"control+r\")]\n if (macro == \"repeat\"):\n return [pressKey(\"control+u\")]\n if (macro == \"transpose\"):\n return [pressKey(\"alt+t\")]\n if (macro == \"cycle\"):\n return [pressKey(\"alt+y\")]\n if (macro == \"delete\"):\n return [pressKey(\"Delete\")]\n if (macro == \"box\"):\n return [pressKey(\"control+enter\")]\n return None\n\ndef nerd_dictation_macro_process(command):\n args = command.split(\" \")\n text_block = \"\"\n ends_in_ha = False\n ends_in_space = False\n if (args[0] == \"huh\") and len(args) > 1:\n args = args[1:]\n if (args[0] == \"the\") and len(args) > 1:\n args = args[1:]\n for i in range(1, len(args)):\n text_block += args[i]\n if i != len(args)-1:\n text_block += \" \"\n if (len(args) > 1):\n if (args[0] == \"quote\"):\n text_block = \" \".join(args[1:])\n return [\n typeText(text_block),\n ]\n for emacs_function in EMACS_COMMANDS:\n if command == emacs_function:\n return emacs_command(\"-\".join(args))\n if (args[0] == \"command\" or args[0] == \"commands\"):\n return emacs_command(handle_text(text_block, \"-\"))\n if (args[0] == \"mark\"):\n if args[1] == \"point\":\n return emacs_command(\"cua-set-mark\")\n if (args[1] == \"thing\"):\n return emacs_command(\"mark-whole-sexp\")\n if (args[1] == \"and\"):\n return emacs_command(\"mark-sexp\")\n if (args[0] == \"see\" and (args[1] == \"if\" or args[1] == \"of\") or\n args[0] == \"cf\" or args[0] == \"senior\"):\n return emacs_command(\"c-if-statement\")\n if (args[0] == \"other\" or\n (args[0] == \"of\" and (args[1] == \"their\" or args[1] == \"there\")) or\n args[0] == \"her\"):\n other_word = args[1]\n if args[0] == \"of\" and len(args) > 2:\n other_word = args[2]\n if (other_word == \"buffer\"):\n return emacs_command(\"other-buffer\")\n if (other_word == \"position\"):\n return emacs_command(\"cua-exchange-point-and-mark\")\n if (other_word == \"client\"):\n return [pressKey(\"alt+Tab\")]\n if (args[0] == \"new\"):\n if (args[1] == \"line\"):\n return emacs_command(\"newline-anywhere\")\n if (args[0] == \"dashed\"):\n return [typeText(handle_text(text_block, \"-\"))]\n if (args[0] == \"bashed\"):\n return [typeText(handle_text(text_block, \"-\", caps=\"caps\"))]\n if (args[0] == \"close\"):\n return [typeText(handle_text(text_block, \"\"))]\n if (args[0] == \"fat\"):\n return [typeText(handle_text(text_block, \"\", caps=\"caps\"))]\n if (args[0] == \"dotted\"):\n return [typeText(handle_text(text_block, \".\"))]\n if (args[0] == \"snake\"):\n return [typeText(handle_text(text_block, \"_\"))]\n if (args[0] == \"bake\"):\n return [typeText(handle_text(text_block, \"_\", caps=\"caps\"))]\n if (args[0] == \"caps\"):\n return [typeText(handle_text(text_block, \" \", caps=\"caps\"))]\n if (args[0] == \"camel\"):\n return [typeText(handle_text(text_block, \"\", caps=\"camel\"))]\n if (args[0] == \"pascal\"):\n return [typeText(handle_text(text_block, \"\", caps=\"pascal\"))]\n if ends_in_space:\n return [\n typeText(handle_text(args[0] + \" \" + text_block, \" \")),\n typeText(\" \"),\n ]\n if ends_in_ha:\n return [\n typeText(handle_text(args[0] + \" \" + text_block, \" \")),\n pressKey(\"enter\"),\n ]\n for i, w in enumerate(args):\n compound_macro = []\n if i > 0:\n compound_macro = [typeText(handle_text(\" \".join(args[:i]), \" \"))]\n middle_macro = process_single_word_macro(args[i])\n if middle_macro != None:\n is_word = True\n not_words = [\"space\", \"back\", \"delete\", \"tab\", \"ha\"]\n if (middle_macro[0][2].split('+')[0] in [\"alt\", \"control\"] or\n args[i] in not_words):\n is_word = False\n if i > 0 and is_word:\n if (args[i-1] not in not_words):\n compound_macro.append(typeText(\" \"))\n for cmd in middle_macro:\n compound_macro.append(cmd)\n if i < len(args) - 1 and is_word:\n if (args[i+1] not in not_words):\n compound_macro.append(typeText(\" \"))\n text_block = \" \".join(args[i+1:])\n sub_macro = nerd_dictation_macro_process(text_block)\n if sub_macro == None:\n sub_macro = [typeText(handle_text(text_block, \" \"))]\n for cmd in sub_macro:\n compound_macro.append(cmd)\n return compound_macro\n # jarvis = parse_jarvis(command)\n # if jarvis != None:\n # return jarvis\n return None\n\ndef nerd_dictation_process(text):\n return handle_text(text, \" \");\n\ndef handle_text(text, seperator, caps=None):\n\n for match, replacement in TEXT_REPLACE_REGEX:\n text = match.sub(replacement, text)\n\n words = text.split(\" \")\n\n for i, w in enumerate(words):\n w_init = w\n w_test = WORD_REPLACE.get(w)\n if w_test is not None:\n w = w_test\n\n if w_init == w:\n for match, replacement in WORD_REPLACE_REGEX:\n w_test = match.sub(replacement, w)\n if w_test != w:\n w = w_test\n break\n\n words[i] = w\n\n # Strip any words that were replaced with empty strings.\n words[:] = [w for w in words if w]\n\n for i in range(0, len(words)):\n if caps == \"camel\" and i != 0:\n words[i] = words[i].capitalize()\n if caps == \"pascal\":\n words[i] = words[i].capitalize()\n if caps == \"caps\":\n words[i] = words[i].upper()\n\n if seperator == \"\":\n text_block = \"\"\n for word in words:\n text_block += word\n return text_block\n\n return seperator.join(words)\n","repo_name":"asamwow/.dotfiles","sub_path":"nerd-dictation/.config/nerd-dictation/nerd-dictation.py","file_name":"nerd-dictation.py","file_ext":"py","file_size_in_byte":13185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40019350061","text":"import configparser\nfrom PIL import Image\n\ndef resize_image(image_path, output_size, background_color):\n img = Image.open(image_path)\n img.thumbnail(output_size, Image.ANTIALIAS)\n \n new_img = Image.new(\"RGB\", output_size, background_color)\n new_img.paste(img, ((output_size[0] - img.size[0]) // 2,\n (output_size[1] - img.size[1]) // 2))\n\n output_path = f\"{output_size[0]}x{output_size[1]}_{image_path}\"\n new_img.save(output_path)\n\ndef main():\n config = configparser.ConfigParser()\n config.read('config.ini')\n image_path = config.get('DEFAULT', 'Image')\n aspect_ratios = config.get('DEFAULT', 'AspectRatios').split(',')\n background_color = config.get('DEFAULT', 'BackgroundColor')\n\n for ratio in aspect_ratios:\n width, height = map(int, ratio.split('x'))\n resize_image(image_path, (width, height), background_color)\n\nif __name__ == \"__main__\":\n main()","repo_name":"abeldantas/image-resizer-pil","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"23604999738","text":"import logging\nimport uuid\nimport os\nfrom flask import Flask, request\nfrom threading import Thread\nfrom google.cloud import storage\nfrom google.cloud.pubsub_v1 import PublisherClient, SubscriberClient\nimport json\nimport sys\nfrom worker import *\nimport base64\n# from google.cloud.pubsub_v1.types import FlowControl\n\n\ndef download_blob(bucket_name, source_blob_name):\n \"\"\"Downloads a blob from the bucket.\"\"\"\n # bucket_name = \"your-bucket-name\"\n # source_blob_name = \"storage-object-name\"\n # destination_file_name = \"local/path/to/file\"\n\n storage_client = storage.Client()\n\n bucket = storage_client.bucket(bucket_name)\n\n # Construct a client side representation of a blob.\n # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve\n # any content from Google Cloud Storage. As we don't need additional data,\n # using `Bucket.blob` is preferred here.\n blob = bucket.blob(source_blob_name)\n dl = blob.download_as_string()\n # blob.download_to_filename(destination_file_name)\n\n print(\n \"Blob was downloaded to \\n {}.\".format(\n dl\n )\n )\n return dl\n\n\nSECRET_KEY = \"VERYCONFIDENTIAL\"\nUPLOAD_FOLDER = \"/uploads/\"\n# CHANGE THESE VALUES ACCORDING TO YOUR APP ENGINE ACCOUNT\nBUCKET_NAME = os.environ.get(\n \"BUCKET_NAME\", \"staging.sss-cc-gae-310003.appspot.com\")\nPROJECT_ID = os.environ.get(\"PROJECT_ID\", \"sss-cc-gae-310003\")\n\n# host flask server\napp = Flask(__name__)\n\n# TODO: Create all topics and subscription if they\n# don't exists\n\n# UPLOAD THIS FILE ONTO YOUR CLOUD STORAGE\nc = download_blob(BUCKET_NAME, 'constants.json')\nconstants = json.loads(c)\n\npub_client = PublisherClient()\nsub_client = SubscriberClient()\nsub_path = sub_client.subscription_path(\n PROJECT_ID, constants[\"job-worker-sub\"])\ntop_path = pub_client.topic_path(PROJECT_ID, constants[\"output-topic\"])\n\n# POST endpoint at '/job/'\n\n\n@app.route('/job/', methods=['POST'])\ndef process_job():\n envelope = json.loads(request.data.decode('utf-8'))\n data_str = base64.b64decode(envelope['message']['data'])\n data = json.loads(data_str)\n message = data[\"URL\"]\n \n # TEST PURPOSES ONLY\n value = redis_client.incr('{}_messages_received'.format(data[\"JobId\"]))\n eid = '2'\n key = ds_client.key('Messages', eid)\n entity = Entity(key=key, exclude_from_indexes=('description',))\n entity['description'] = \"message_receieved\"\n entity['value'] = value\n ds_client.put(entity)\n\n # to prevent processing of same links\n job_id = data[\"JobId\"]\n\n # lists all memebrs of the set with name 'job_id'\n members = redis_client.smembers(job_id)\n\n # if empty\n if len(members) == 0:\n redis_client.sadd(job_id, message)\n # if not empty\n else:\n # if message is a member of job_id\n # we acknowledge the message and skip processing\n if redis_client.sismember(job_id, message):\n # pay_load.ack()\n value = redis_client.incr('{}_messages_skipped'.format(data[\"JobId\"]))\n # TEST PURPOSES ONLY\n eid = '4'\n key = ds_client.key('Messages',eid)\n entity = Entity(key=key, exclude_from_indexes=('description',))\n entity['description'] = \"messages_skipped\"\n entity['value'] = value\n ds_client.put(entity)\n return 'OK', 200\n # else add to set and process\n else:\n redis_client.sadd(job_id, message)\n\n prof_obs = []\n links = []\n threads = []\n if data[\"Type\"] == constants[\"faculty\"]:\n parse_faculty_page(message, data)\n elif data[\"Type\"] == constants[\"profile\"]:\n extract_links_isearch(message, data)\n elif data[\"Type\"] == constants[\"pdf\"]:\n parse_pdf(message, data)\n else:\n extract_links_others(message, data)\n # pay_load.ack()\n return 'OK', 200\n\n# socket io listeners and event emitters start here\n\n\n@app.errorhandler(500)\ndef server_error(e):\n logging.exception('An error occurred during a request.')\n logging.exception('Error was ----> \\n{}\\n'.format(e))\n return \"\"\"\n An internal error occurred:
    {}
    \n See logs for full stacktrace.\n \"\"\".format(e), 500\n\n\n# TODO: listen to response subscription\n# listening to subscription for output topic\nif __name__ == '__main__':\n # print('starting listening to output sub')\n # t1 = Thread(target=output_listener_thread)\n # t1.start()\n print('starting listening to server events')\n # socketio.run(\n # app, host='0.0.0.0', port=os.environ.get('PORT', 8080)\n # )\n","repo_name":"ssahare-hub/re-search-aggregator","sub_path":"app-tier/apptier_server.py","file_name":"apptier_server.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"75076438338","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.db import models\nfrom .models import menu as Menu\nfrom order.models import Order\nfrom django.db.models import Sum\nimport json\n# Create your views here.\n\ndef queryMenu(request):\n # menu = [{'typeName': '快餐类','''menuContent':[{'name':'炸鸡'},{'name':'鸡腿'}]},{}]\n data = json.loads(request.body)\n username = data['username']\n menu = []\n typeName = []\n feed_list = []\n feed = []\n feed = Order.objects.filter(username=username).values('food_name').annotate(numb=Sum('number')).values('food_name','numb')[0:5]\n if len(feed) == 0:\n feed = Order.objects.values('food_name').annotate(numb=Sum('number')).values('food_name','numb')[0:5]\n for it in feed:\n item = Menu.objects.filter(name=it['food_name'],status='启用')\n if item:\n item = item[0]\n feed_list.append({'name':item.name,'src':str(item.src),'sales':item.sales,'rating':round(item.rating,1),'numb':0, 'price':item.price})\n menu.append({'typeName': '为你推荐', 'menuContent': feed_list})\n typeName = Menu.objects.all().values('typeName').order_by('typeName').distinct()\n for it in typeName:\n my_dict = {}\n my_dict['typeName'] = it['typeName']\n menuContent = Menu.objects.filter(typeName=it['typeName'],status='启用')\n list = []\n for item in menuContent:\n list.append({'name':item.name,'src':str(item.src),'sales':item.sales,'rating':round(item.rating,1),'numb':0, 'price':item.price})\n my_dict['menuContent'] = list\n if len(list) != 0:\n menu.append(my_dict)\n tmp = json.dumps(menu)\n return HttpResponse(tmp)","repo_name":"fistraiser/weixin","sub_path":"backend/queryMenu/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"80"} +{"seq_id":"22881405875","text":"segundos = input(\"Por favor, entre com o número de segundos que deseja converter: \")\r\ntotal_segundos = int(segundos)\r\n\r\ndias = total_segundos // 86400\r\nresto_seg1 = total_segundos % 86400\r\n\r\nhoras = resto_seg1 // 3600\r\nresto_seg2 = resto_seg1 % 3600\r\n\r\nminutos = resto_seg2 // 60\r\nrest_seg_final = resto_seg2 % 60\r\n\r\nprint(dias, \"dias,\", horas, \"horas,\", minutos, \"minutos e\", rest_seg_final, \"segundos.\")","repo_name":"heitor19oliveira/Python-1","sub_path":"segundos.py","file_name":"segundos.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"33217779112","text":"import time\nimport serial\nimport comsManagerAlpha\nimport ledManager\n\nled = ledManager.LedManager()\ncoms = comsManagerAlpha.ComsManager()\n\ncoms.clearBufferOut()\ncoms.clearBufferIn()\n\ncoms.sendSerialData(13,222,1)\nprint(\"--------\")\ncoms.waitUntilDataIn()\ncoms.receiveSerialData() \n \ndataList = coms.getData()\nprint(\"1:\" + str(dataList[0]) + \" 2:\" + str(dataList[1]) + \" 3:\" + str(dataList[2]) + \" 4:\" + str(dataList[3]) + \" 5:\" + str(dataList[4]) + \" 6:\" + str(dataList[5]))\nled.test()\n\ncoms.close() \n \n","repo_name":"kaalodabney/Delta-Autonomous-Pet-Bot","sub_path":"RPI/mainSerialTest.py","file_name":"mainSerialTest.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"15251503240","text":"import re\n\ntest_input_1 = [\n '0 <-> 2',\n '1 <-> 1',\n '2 <-> 0, 3, 4',\n '3 <-> 2, 4',\n '4 <-> 2, 3, 6',\n '5 <-> 6',\n '6 <-> 4, 5'\n]\n\nwith open(\"data.txt\") as file:\n input_data = file.read().split('\\n')\n\n\ndef find_group(program_map, found, program_id):\n potential_new_programs = program_map.get(program_id)\n\n if found.union(potential_new_programs) == found:\n return found\n\n found = found.union(potential_new_programs)\n\n for potential in potential_new_programs:\n found = found.union(find_group(program_map, found, potential))\n\n return found\n\n\ndef group_programs(pipe_list):\n program_map = dict()\n\n for line in pipe_list:\n regex = re.search('(\\d+) <-> ([, \\d]+)', line)\n program_id = int(regex.group(1))\n connected = set(int(x) for x in regex.group(2).split(','))\n program_map.update({program_id: connected})\n\n return len(find_group(program_map, {0}, 0))\n\n\ndef main():\n test_1 = group_programs(test_input_1)\n print(\"test_1:\", test_1)\n\n answer = group_programs(input_data)\n print(\"answer:\", answer)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mkierc/advent-of-code","sub_path":"2017/src/day_12/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38773229076","text":"from sympy import Sum, var, poly\nfrom .sage_compatibility import Int, Rat, Number, prod, latex, factorial, binomial\nfrom .qsym import qsym\nfrom .global_vars import max_weight, num, mzv_alg, mono_to_basis, mhs_to_mono, mzv_mono, mzv_to_mono, weights, mhs_basis\nfrom .rational import MHS_approx, red\nfrom .misc import psc, psc_, D_add, comps, comps_i, lists, wt\nfrom .tex import error_tex, tex_write, tstr, monomial, un_texify, tex_write_single, fix_pow, fix_prod\nfrom .misc import D_add, wt, bn, decomps, S_min_v\nfrom IPython.display import display, Math\n\n\ndef _unit():\n return (0,tuple(0 for _ in range(len(mzv_alg()))))\n\ndef _weight(x):\n return x[0]\n\ndef _mul(x,y):\n return {(x[0]+y[0],tuple(x[1][i]+y[1][i] for i in range(len(mzv_alg())))):1}\n\nclass MhsAlg():\n def __init__(self, s=0, err=99999):\n if isinstance(s,Number):\n self.data = {}\n if s != 0:\n self.data[_unit()] = s\n self.err = err\n self.desc = latex(s)\n elif isinstance(s,MhsAlg):\n self.data = dict(s.data)\n self.err = min(s.err, err)\n self.desc = s.desc\n elif isinstance(s,dict):\n self.data = dict(s)\n self.err = err\n self.desc = None\n elif isinstance(s,type(_unit())):\n self.data = {s: 1}\n self.err = err\n self.desc = None\n elif isinstance(s,qsym):\n T = sum(s.data[q] * Hp(*q) for q in s.data)\n self.data = T.data\n self.err = T.err\n self.desc = None\n else:\n raise ValueError(\"Cannot create element of MHS algebra from data type %s\"%str(type(s)))\n \n def __repr__(self):\n if self.desc is not None:\n self.disp()\n return ''\n \n def disp(self):\n \"\"\"Displays a human-readable description, if one is available\"\"\"\n if self.desc is None:\n print(\"\")\n else:\n display(Math(self.desc))\n return None\n \n \n def mzv(self, err=None, reverse=False,p='p',mot=False,tex=True):\n \"\"\"Displays an element in the MZV basis\"\"\"\n if err is not None:\n T = MhsAlg(self)\n T.aerr(err)\n return T.mzv(reverse=reverse,p=p,mot=mot)\n self.clean()\n A = tex_write_single(self.data,\n lambda x:fix_prod(fix_pow(p,x[0]-wt(x[1])),monomial([r\"\\zeta_p\"+tstr(q) for q in mzv_alg()],x[1])),\n lambda x:(x[0],wt(x[1])),\n err=self.err,\n var='p')\n if tex:\n return Math(A)\n else:\n return A\n \n def mzv_old(self, err=None, reverse=False,p='p',mot=False,tex=True):\n \"\"\"Displays an element in the MZV basis\"\"\"\n if err is not None:\n T = MhsAlg(self)\n T.aerr(err)\n return T.mzv(reverse=reverse,p=p,mot=mot)\n self.clean()\n if reverse:\n A = tex_write({(x[0]-wt(x[1]),x[1]):self.data[x] for x in self.data},\n lambda x:monomial([r\"\\zeta\"+(r\"^{\\mathfrak{dr}}\" if mot else \"_p\")+tstr(q) for q in mzv_alg()],x[1]),\n lambda x:(wt(x[1]),) + x[1],\n lambda x:monomial([p],[_weight(x)]),\n lambda x:_weight(x),\n err=self.err,\n first=not mot,\n var=r'\\mathbb{L}' if mot else 'p')\n else:\n A = tex_write({(x[0]-wt(x[1]),x[1]):self.data[x] for x in self.data},\n lambda x:monomial([p],[_weight(x)]),\n lambda x:_weight(x),\n lambda x:monomial([r\"\\zeta\"+(r\"^{\\mathfrak{dr}}\" if mot else \"_p\")+tstr(q) for q in mzv_alg()],x[1]),\n lambda x:(wt(x[1]),) + x[1],\n err=self.err,\n first=not mot,\n var=r'\\mathbb{L}' if mot else 'p')\n if tex:\n return Math(A)\n else:\n return un_texify(A)\n \n def mhs(self,err=None):\n \"\"\"Displays an element in the MHS basis\"\"\"\n if err is not None:\n T = MhsAlg(self)\n T.aerr(err)\n return T.mhs()\n self.clean()\n D = {}\n e = self.err\n for x in self.data:\n if wt(x[1]) > max_weight():\n e = min(e,_weight(x))\n else:\n i = mzv_mono().index(x[1])\n for j in range(num()):\n D_add(D,(x[0]-wt(x[1]),j),self.data[x]*mono_to_basis()[i][j])\n if i != 0:\n e = min(e,x[0] + max_weight() + 1)\n K = list(D.keys())\n for x in K:\n if x[0]+weights()[x[1]] >= e:\n D.pop(x)\n T = tex_write(D,\n lambda x:monomial(['p'],[x[0]+weights()[x[1]]]),\n lambda x:x[0]+weights()[x[1]],\n lambda x:\"H_{p-1}\"+tstr(mhs_basis()[x[1]]) if x[1] != 0 else \"1\",\n lambda x:(weights()[x[1]],) + (x[0],),\n e,\n True)\n return Math(T)\n \n \n \n def clean(self):\n K = list(self.data.keys())\n for x in K:\n if self.data[x] == 0 or x[0] >= self.err:\n self.data.pop(x)\n\n def __add__(self, s):\n if isinstance(s,Number):\n return self + MhsAlg(s)\n elif isinstance(s,MhsAlg):\n T = MhsAlg(s)\n T.err = min(T.err, self.err)\n for x in self.data:\n if self.data[x] != 0 and _weight(x) < T.err:\n D_add(T.data,x,self.data[x])\n T.desc = None\n return T\n\n def __mul__(self, s):\n if isinstance(s,Number):\n if s == 0:\n return MhsAlg()\n T = MhsAlg(self)\n T.clean()\n for x in T.data:\n T.data[x] *= s\n T.desc = None\n return T\n elif isinstance(s,MhsAlg):\n T = MhsAlg()\n T.err = min(self.err+s.v(),s.err+self.v())\n for x in self.data:\n for y in s.data:\n if self.data[x] != 0 and s.data[y] != 0 and _weight(x)+_weight(y) 0:\n return self*self**(n-1)\n elif n < 0:\n return self.inv() ** (-n)\n\n def v(self):\n \"\"\"Computes a lower bound for valuation (conjecturally the liminf)\"\"\"\n err = self.err\n self.clean()\n for x in self.data:\n err = min(err,x[0])\n return err\n\n def inv(self):\n \"\"\"Find the multiplicative inverse, if it exists\"\"\"\n self.clean()\n VV = self.v()\n u = len(mzv_alg()) * (0,)\n for x in self.data:\n if x[0] == VV and x[1] != mzv_mono()[0]:\n print(\"Element is not invertible\")\n return None\n c = self.data[(VV,u)]\n T = MhsAlg(1) - self*P(-VV)/c\n A = MhsAlg(1)\n B = MhsAlg(1)\n A.err = self.err\n B.err = self.err\n for n in range(min(A.err + 1,15)):\n B *= T\n A += B\n if B.data == {}:\n break\n if B.data != {}:\n A.aerr(16)\n return A/c*P(-VV)\n \n def __div__(self,s):\n if isinstance(s,Number):\n return self * (Rat(1)/s)\n if isinstance(s,MhsAlg):\n return self*s.inv()\n \n def __rdiv__(self,s):\n return s * self.inv()\n \n def __neg__(self):\n return (-1)*self\n \n def aerr(self,err):\n self.err = min(self.err, err)\n return self\n \n def add(self,s):\n \"\"\"Adds s to self, leaving self in place\"\"\"\n if isinstance(s,Number):\n D_add(self.data,_unit(),s)\n elif isisntance(s,MhsAlg):\n for x in s.data:\n D_add(self.data,x,s.data[x])\n return None\n \n def Gm(self, r):\n \"\"\"Acts on an element by an element r in G_m(Q)\"\"\"\n T = MhsAlg(self)\n for x in T.data:\n T.data[x] *= r ** (weight(x) - x[0])\n T.desc = None\n return T\n \n def Gmp(self):\n \"\"\"Acts on an element by (p) in G_m(Q_{p\\to\\infty})\"\"\"\n T = MhsAlg()\n for x in self.data:\n T.data[_weight(x), x[1]] = self.data[x]\n T.desc = None\n return T\n \n def new_e(self, p):\n mzv = [0 for i in range(len(mzv_alg()))]\n \n def e(self, p):\n \"\"\"Evaluate at a prime p\"\"\"\n S = 0\n self.clean()\n k = self.err\n for i in range(num()):\n L = mzv_mono()[i]\n T = 0\n v = 99999\n for x in self.data:\n if x[1] == L:\n T = red(T + self.data[x] * Rat(p)**x[0], p, k)\n v = min(v, x[0])\n if T != 0:\n Q = mono_to_basis()[i]\n S += T*sum(Q[j]*Rat(p)**(weights()[j]-wt(L))*MHS_approx(p,k - v - weights()[j] + wt(L),p-1,*mhs_basis()[j]) for j in range(num()) if Q[j]!=0)\n return red(S, p, k)\n\ndef P(r):\n \"\"\"p^r\"\"\"\n T = MhsAlg((r,_unit()[1]))\n T.desc = \"p^r\"\n return T\n\ndef Hp(*s):\n \"\"\"Multiple harmonic sum H_{p-1}(s)\"\"\"\n T = P(-sum(s))*hp(*s)\n T.desc = \"H_{p-1}\" + tstr(s)\n return T\n","repo_name":"julianrosen/mhs","sub_path":"mhs_alg.py","file_name":"mhs_alg.py","file_ext":"py","file_size_in_byte":9886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"9018956252","text":"# your code goes here\n#import numpy as np\n\nDvalue = 0.565\na = [0.44,0.14,0.81,0.93,0.05]\na.sort()\nb = [(i+1)/len(a) for i in range(len(a))]\ndp = [b[i]-a[i] for i in range(len(a))]\ndn = [a[i]-i/len(a) for i in range(len(a))]\n\nmaxd = max(max(dp),max(dn))\nprint (maxd)\n\nif (maxd List[Dict[str, Union[str, None]]]:\n response = requests.get(URL_TO_DBPEDIA_SERVICE, params={\"text\": text}, headers={\"accept\": \"application/json\"})\n if response:\n json = response.json()\n if \"Resources\" in json.keys():\n for result in json[\"Resources\"]:\n entry = {}\n for dbpedia_key, neo4j_key in key_mapping.items():\n entry[neo4j_key] = result.get(dbpedia_key, None)\n yield entry\n\n\ndef extract_dbpedia_ners_from_text(text: str, key_mapping: Dict[str, str]) -> List[Dict[str, Union[str, None]]]:\n for entry in request_dbpedia_ners_from_text(text, key_mapping):\n del entry[\"types\"]\n yield entry\n\n\ndef _make_load_dbpedia_dump_statement(appendix, filename):\n load_from_csv = \"\"\"\n USING PERIODIC COMMIT 1000\nLOAD CSV WITH HEADERS FROM 'file:///%s' AS row\n FIELDTERMINATOR \"\\t\"\n MATCH (p:Paragraph) WHERE p.id = row.p_id\n MERGE (d:DBConcept {uri : row.uri})\n\n CREATE (p)-[\n :MENTIONS {surfaceForm: row.surfaceForm, support : row.support, offset : row.offset, similarityScore : row.similarityScore, percentageOfSecondRank : row.percentageOfSecondRank}\n ]->(d)\n \"\"\"\n return (load_from_csv + appendix) % filename\n\n\ndef make_load_dbpedia_dump_statement_with_types(filename):\n appendix = \"\"\"\n MERGE (w:WDConcept {uri : row.type})\n MERGE (d)-[:rdf_type]->(w)\n \n \"\"\"\n return _make_load_dbpedia_dump_statement(appendix, filename)\n\n\ndef make_load_dbpedia_dump_statement_without_types(filename):\n return _make_load_dbpedia_dump_statement(\"\", filename)\n\n\ndef check_if_sids_in_ners_inject_if_not():\n tmp = load_tsv(DBPEDIA_NERS)\n if len(tmp) == 0:\n log(f\"{DBPEDIA_NERS} is empty, cannot write any NEs\", LogLevel.WARNING)\n elif \"s_id\" in tmp[0].keys():\n return\n else:\n log(\"No sentences ids present, injecting..\")\n inject_sids_from_pids(DBPEDIA_NERS)\n log(\"Done.\")\n\n\n@timer\ndef write_dbpedia_annotations_to_graph(graph: HelloWorldExample):\n log(\"Annotating sentences with dbpedia..\")\n check_if_sids_in_ners_inject_if_not()\n statement = f\"\"\"\n USING PERIODIC COMMIT 5000\n LOAD CSV WITH HEADERS FROM 'file:///{DBPEDIA_NERS}' AS row\n FIELDTERMINATOR \"\\t\"\n MATCH (s:Sentence)\n WHERE s.id = row.s_id\n MERGE (d:DBConcept {{uri : row.uri}})\n CREATE (s)-[\n :MENTIONS {{surfaceForm: row.surfaceForm, support : row.support, offset : row.offset, similarityScore : row.similarityScore, percentageOfSecondRank : row.percentageOfSecondRank}}\n ]->(d)\n \"\"\"\n graph.execute_query_without_transaction(statement)\n log(\"Done.\")\n\n\ndef annotate_dbpedia_spotlight_to_sentences(graph: HelloWorldExample):\n if not Path(DBPEDIA_NERS).exists():\n log(f\"File with DBpedia annotations does not exist ({DBPEDIA_NERS}).\", LogLevel.WARNING)\n else:\n write_dbpedia_annotations_to_graph(graph)\n\n\ndef collect_pid_from_file(loaded, pid_key=\"p_id\"):\n return set(e[pid_key] for e in loaded)\n\n\ndef load_paragraph_meta_without_double_p_ids(sth, pid_key=\"p_id\"):\n doggu = set()\n hottu = list()\n for e in sth:\n if e[pid_key] in doggu:\n continue\n else:\n hottu.append(e)\n doggu.update(e[pid_key])\n return hottu\n\n\ndef make_dbpedia_dump():\n DBPEDIA_KEY_MAPPING = {\"@URI\": \"uri\",\n \"@support\": \"support\",\n \"@types\": \"types\",\n \"@surfaceForm\": \"surfaceForm\",\n \"@offset\": \"offset\",\n \"@similarityScore\": \"similarityScore\",\n \"@percentageOfSecondRank\": \"percentageOfSecondRank\"\n }\n paragraph_paths = load_tsv(PARAGRAPH_META)\n already_parsed = set()\n log(\"Making dbpedia dump..\")\n prev_run = load_tsv(DBPEDIA_NERS) if Path(DBPEDIA_NERS).exists() else []\n already_parsed = collect_pid_from_file(prev_run)\n sth = load_paragraph_meta_without_double_p_ids(paragraph_paths)\n todo = list(filter(lambda elem: not elem[\"p_id\"] in already_parsed, sth))\n if len(already_parsed):\n log(f\"Found {len(already_parsed)} already annotated sentences, {len(todo)} left to do..\")\n\n with open(DBPEDIA_NERS, \"w\", encoding=\"utf-8\") as outf:\n header = [\"p_id\", \"uri\", \"paragraph_path\", \"support\", \"surfaceForm\", \"offset\", \"similarityScore\",\n \"percentageOfSecondRank\"]\n without_writer = csv.DictWriter(outf, header, delimiter=\"\\t\")\n without_writer.writeheader()\n for e in prev_run:\n without_writer.writerow(e)\n for paragraph_meta in tqdm(todo):\n p_id = paragraph_meta[\"p_id\"]\n path = paragraph_meta[\"paragraph_path\"]\n paragraph = load_file(path)\n for ner in extract_dbpedia_ners_from_text(paragraph, DBPEDIA_KEY_MAPPING):\n ner[\"p_id\"] = p_id\n ner[\"paragraph_path\"] = path\n without_writer.writerow(ner)\n\n\ndef filter_for_wikidata_concepts(candidates: List[str]):\n return [uri for uri in candidates if uri.startswith(\"http://www.wikidata.org/entity/Q\")]\n\n\ndef get_wikidata_entry_from_global_thingy(uri, http):\n response = http.get(WD_GFS_ENDPOINT, params={\"s\": uri},\n headers={\"accept\": \"application/json\"})\n if response:\n return filter_for_wikidata_concepts(response.json()[\"locals\"])\n else:\n return []\n\n\ndef get_wikidata_equivalent_for_dbpedia_uri(uri, http):\n dbpedia_query = f\"\"\"prefix owl:\n SELECT DISTINCT ?sameAs WHERE {{\n <{uri}> owl:sameAs ?sameAs \n FILTER ( strstarts(str(?sameAs), \"http://www.wikidata.org/\") )\n }}\"\"\"\n response = http.get(URL_TO_DBPEDIA_ENDPOINT, params={\"query\": dbpedia_query},\n headers={\"accept\": \"application/json\"})\n\n resp = response.json()\n entries = []\n if resp:\n results = resp[\"results\"][\"bindings\"]\n if len(results) == 0:\n results_from_global = get_wikidata_entry_from_global_thingy(uri, http)\n if len(results_from_global) == 0:\n tqdm.write(f\"[WARNING] Couldn't find link for {uri} in either dbpedia or global!\")\n entries.extend(results_from_global)\n else:\n entries.extend(item[\"sameAs\"][\"value\"] for item in results)\n return entries\n\n\ndef _split_ambiguous_from_unambiguous_linkings(data):\n linkings = {}\n ambiguous = []\n unambiguous = []\n for entry in data:\n tmp = linkings.get(entry[\"db_uri\"], [])\n tmp.append(entry[\"wd_uri\"])\n linkings[entry[\"db_uri\"]] = tmp\n for source, targets in linkings.items():\n if len(targets) == 1:\n unambiguous.append({\"db_uri\": source, \"wd_uri\": targets[0]})\n else:\n for target in targets:\n ambiguous.append({\"db_uri\": source, \"wd_uri\": target, \"keep\": \"\"})\n return ambiguous, unambiguous\n\n\ndef split_ambiguous_from_unambiguous_linkings(data):\n ambiguous, _ = _split_ambiguous_from_unambiguous_linkings(data)\n dump_tsv(DBPEDIA_TO_WIKIDATA_AMBIGUOUS, ambiguous)\n\n\ndef make_dbpedia_to_wikidata_dump(data, dump_path):\n http = create_retrying_session()\n links = []\n for item in tqdm(data):\n sameAs_uris = get_wikidata_equivalent_for_dbpedia_uri(item, http)\n for uri in sameAs_uris:\n links.append({\"db_uri\": item, \"wd_uri\": uri, \"keep\": \"\"})\n split_ambiguous_from_unambiguous_linkings(links)\n dump_tsv(dump_path, links)\n\n\ndef sanity_check_db_wd_linking():\n load = load_tsv(DBPEDIA_TO_WIKIDATA)\n result = True\n expected_fieldnames = {\"db_uri\", \"wd_uri\", \"keep\"}\n actual_fieldnames = set(load[0].keys())\n if actual_fieldnames != expected_fieldnames:\n log(\n f\"DBpedia -> Wikidata linking has unexpected fieldnames! Actual: {', '.join(actual_fieldnames)}; Expected: {', '.join(expected_fieldnames)}\",\n LogLevel.ERROR)\n result = False\n if \"keep\" in actual_fieldnames:\n if all(line[\"keep\"].strip() == \"\" for line in load):\n log(f\"DBpedia -> Wikidata linking has no annotation in the `keep` column!\", LogLevel.ERROR)\n result = False\n return result\n\n\nLINKING_MANUAL = f\"\"\"You need to do the manual annotation part in {DBPEDIA_TO_WIKIDATA_AMBIGUOUS}. See README.md for instructions.\"\"\"\n\n\ndef filter_linking_for_applicables_and_merge(force=False):\n disambiguated = {}\n for line in load_tsv(DBPEDIA_TO_WIKIDATA_AMBIGUOUS):\n if len(line[\"keep\"].strip()) > 0:\n disambiguated[line[\"db_uri\"]] = line[\"wd_uri\"]\n ambiguous, unambiguous = _split_ambiguous_from_unambiguous_linkings(load_tsv(DBPEDIA_TO_WIKIDATA))\n already_logged = set()\n for amb in ambiguous:\n if amb[\"db_uri\"] not in disambiguated and amb[\"db_uri\"] not in already_logged:\n if not force:\n log(f\"{amb['db_uri']} not disambiguated in {DBPEDIA_TO_WIKIDATA_AMBIGUOUS}! Skipping.\", LogLevel.WARNING)\n already_logged.add(amb[\"db_uri\"])\n unambiguous.extend({\"db_uri\": key, \"wd_uri\": value} for key, value in disambiguated.items())\n dump_tsv(DBPEDIA_TO_WIKIDATA_INTERNAL, unambiguous)\n encountered_errors = len(already_logged)\n if not force:\n log(f\"Encountered {encountered_errors} missing links.\", LogLevel.WARNING)\n return encountered_errors\n\n\n@timer\ndef link_dbpedia_with_wikidata(graph: HelloWorldExample, force=False):\n query = f\"\"\" USING PERIODIC COMMIT 5000\n LOAD CSV WITH HEADERS FROM 'file:///{DBPEDIA_TO_WIKIDATA_INTERNAL}' AS row\n FIELDTERMINATOR \"\\t\"\n MERGE (db:DBConcept {{uri : row.db_uri}})\n MERGE (wd:WDConcept {{uri : row.wd_uri}})\n MERGE (db)-[:owl_sameAs]->(wd)\n MERGE (db)<-[:owl_sameAs]-(wd)\n \"\"\"\n if not Path(DBPEDIA_TO_WIKIDATA).is_file():\n log(\n f\"No link dump found at {DBPEDIA_TO_WIKIDATA}, building now (This will require human intervention later!)..\")\n select_query = \"\"\"MATCH (d:DBConcept)\n RETURN DISTINCT d.uri\n \"\"\"\n db_uris = [e[\"d.uri\"] for e in graph.select(select_query)]\n make_dbpedia_to_wikidata_dump(db_uris, DBPEDIA_TO_WIKIDATA)\n log(\"Done.\")\n log(LINKING_MANUAL)\n sys.exit(1)\n else:\n encountered_errors = filter_linking_for_applicables_and_merge(force)\n if not encountered_errors or force:\n graph.execute_query_without_transaction(query)\n else:\n log(LINKING_MANUAL)\n sys.exit(1)\n\n\ndef query_wd_for_P31(batch, http):\n baseuri = \"https://query.wikidata.org/sparql\"\n query = f\"\"\"PREFIX wd: \nPREFIX rdfs: \nPREFIX skos: \n\nSELECT DISTINCT ?instance ?class \n WHERE {{\n VALUES (?instance) {{\n {' '.join(f\"(<{elem['wd.uri']}>)\" for elem in batch)}\n }}\n ?instance wd:P31 ?class.\n }}\n\"\"\"\n response = http.get(baseuri, params={\"query\": query},\n headers={\"accept\": \"application/json\"})\n resp = response.json()\n entries = []\n if resp:\n results = resp[\"results\"][\"bindings\"]\n for res in results:\n entries.append((res[\"instance\"][\"value\"], res[\"class\"][\"value\"]))\n\n return entries\n\n\n@timer\ndef _get_classes_for_wd(graph: HelloWorldExample):\n all_uris = graph.select(\"MATCH (wd:WDConcept) RETURN DISTINCT wd.uri\")\n http = create_retrying_session()\n data = []\n batches = [all_uris[i:i + 100] for i in range(0, len(all_uris), 100)]\n for batch in tqdm(batches):\n for instance, clazz in query_wd_for_P31(batch, http):\n data.append({\n \"instance\": instance, \"class\": clazz})\n dump_tsv(WD_CLASSES, data)\n\n\ndef get_classes_for_wd(graph: HelloWorldExample):\n if not Path(WD_CLASSES).is_file():\n log(f\"{WD_CLASSES} does not exist, creating..\")\n _get_classes_for_wd(graph)\n\n query = f\"\"\"\n USING PERIODIC COMMIT 5000\n LOAD CSV WITH HEADERS FROM 'file:///{WD_CLASSES}' AS row\n FIELDTERMINATOR \"\\t\"\n MATCH (a:WDConcept)\n WHERE a.uri = row.instance\n MERGE (b:WDConcept {{uri: row.class}})\n MERGE (a)-[:wd_P31]->(b)\n \"\"\"\n graph.execute_query_without_transaction(query)\n\n\ndef query_wd_for_P279(batch, http):\n baseuri = \"https://query.wikidata.org/sparql\"\n query = f\"\"\"PREFIX wd: \n PREFIX rdfs: \n PREFIX skos: \n\n SELECT DISTINCT ?class ?superclass \n WHERE {{\n VALUES (?class) {{\n {' '.join(f\"(<{elem}>)\" for elem in batch)}\n }}\n ?class wd:P279 ?superclass.\n }}\n \"\"\"\n response = http.get(baseuri, params={\"query\": query},\n headers={\"accept\": \"application/json\"})\n resp = response.json()\n entries = []\n if resp:\n results = resp[\"results\"][\"bindings\"]\n for res in results:\n entries.append((res[\"class\"][\"value\"], res[\"superclass\"][\"value\"]))\n\n return entries\n\n\ndef _get_hierarchy_for_wd(graph: HelloWorldExample):\n uris_to_query = [uri[\"class.uri\"] for uri in graph.select(\"MATCH (class:WDConcept) RETURN DISTINCT class.uri\")]\n http = create_retrying_session()\n data = []\n depth = 5\n already_queried = set()\n for _ in tqdm(range(depth)):\n tmp = []\n batches = [uris_to_query[i:i + 100] for i in range(0, len(uris_to_query), 100)]\n for batch in tqdm(batches, leave=False):\n for clazz, superclazz in query_wd_for_P279(batch, http):\n already_queried.add(clazz)\n tmp.append({\n \"superclass\": superclazz, \"class\": clazz})\n uris_to_query.clear()\n for new in tmp:\n if new[\"superclass\"] not in already_queried:\n uris_to_query.append(new[\"superclass\"])\n data.append(new)\n\n dump_tsv(WD_HIERARCHY, data)\n\n\n@timer\ndef get_class_hierarchy_for_wd(graph: HelloWorldExample):\n log(\"Writing wd:P279 relations..\")\n if not Path(WD_HIERARCHY).is_file():\n log(f\"{WD_HIERARCHY} does not exist, creating..\")\n _get_hierarchy_for_wd(graph)\n query = f\"\"\"\n USING PERIODIC COMMIT 5000\n LOAD CSV WITH HEADERS FROM 'file:///{WD_HIERARCHY}' AS row\n FIELDTERMINATOR \"\\t\"\n MERGE (class:WDConcept {{uri : row.class}})\n MERGE (super:WDConcept {{uri : row.superclass}})\n MERGE (class)-[:wd_P279]->(super)\n \"\"\"\n graph.execute_query_without_transaction(query)\n log(\"Done.\")\n\n\ndef query_wd_for_label(batch, http):\n query = f\"\"\"PREFIX wd: \n PREFIX rdfs: \n PREFIX skos: \n\n SELECT DISTINCT ?uri ?uriLabel \n WHERE {{\n VALUES (?uri) {{\n {' '.join(f\"(<{elem['wd.uri']}>)\" for elem in batch)}\n }}\n SERVICE wikibase:label {{\n bd:serviceParam wikibase:language \"en\" .\n }}\n }}\n \"\"\"\n baseuri = \"https://query.wikidata.org/sparql\"\n\n response = http.get(baseuri, params={\"query\": query},\n headers={\"accept\": \"application/json\"})\n resp = response.json()\n entries = []\n if resp:\n results = resp[\"results\"][\"bindings\"]\n for res in results:\n entries.append((res[\"uri\"][\"value\"], res[\"uriLabel\"][\"value\"]))\n return entries\n\n\ndef _get_label_for_wd(graph: HelloWorldExample):\n query = \"\"\"MATCH (wd:WDConcept) RETURN DISTINCT wd.uri\"\"\"\n all_uris = graph.select(query)\n batches = [all_uris[i:i + 100] for i in range(0, len(all_uris), 100)]\n data = []\n\n http = create_retrying_session()\n for batch in tqdm(batches):\n for uri, uri_label in query_wd_for_label(batch, http):\n data.append({\"uri\": uri, \"uri_label\": uri_label})\n dump_tsv(WD_LABELS, data)\n\n\n@timer\ndef get_label_for_wd(graph: HelloWorldExample):\n log(\"Setting labels to wikidata concepts..\")\n if not Path(WD_LABELS).is_file():\n log(f\"{WD_LABELS} does not exist, creating..\")\n _get_label_for_wd(graph)\n\n query = f\"\"\"\n USING PERIODIC COMMIT 5000\n LOAD CSV WITH HEADERS FROM 'file:///{WD_LABELS}' AS row\n FIELDTERMINATOR \"\\t\"\n MATCH (a:WDConcept)\n WHERE a.uri = row.uri\n SET a.label = row.uri_label\n \"\"\"\n graph.execute_query_without_transaction(query)\n log(\"Done.\")\n\n\nhttp = create_retrying_session()\n\n\ndef extract_bindings_or_empty_list(response: requests.Response) -> Union[List[Dict[str, Any]], List]:\n if not response:\n return []\n else:\n return response.json()[\"results\"][\"bindings\"]\n\n\ndef get_label_and_uri_from_wikidata_for_label_and_type(label, type):\n query = f\"\"\"\n PREFIX wd: \n SELECT DISTINCT ?uri ?label \n WHERE {{\n VALUES(?label) {{\n ( \"{label}\" )\n }}\n ?uri ?p ?label\n ; wd:P31/wd:P279* <{type}>\n\n SERVICE wikibase:label {{\n bd:serviceParam wikibase:language \"en\" .\n }}\n }}\"\"\"\n\n r = http.get(WD_SPARQL_ENDPOINT, params={'format': 'json', 'query': query})\n return r\n\n\nstupid_capitalization = {\n \"Of\": \"of\",\n \"And\": \"and\",\n \"For\": \"for\",\n \"The\": \"the\"\n}\n\n\ndef make_wikidata_not_cry(string):\n return \" \".join(\n stupid_capitalization[word] if word in stupid_capitalization.keys() else word for word in string.split(\" \"))\n\n\ndef make_entites_csv(entity_file_path, entity_uri, entity_label):\n labels = set()\n from pathlib import Path\n label_mapping = {}\n if Path(entity_file_path).is_file():\n with open(entity_file_path, encoding=\"utf-8\") as f:\n reader = csv.DictReader(f, delimiter=\";\")\n for line in reader:\n label = line[entity_label]\n tmp = label_mapping.get(label, [])\n tmp.append(line[\"uri\"])\n label_mapping[label] = tmp\n else:\n log(f\"File {entity_file_path} with label mapping is empty.\", LogLevel.WARNING)\n with open(\"../data/speaker.tsv\", encoding=\"utf-8\") as f:\n reader = csv.DictReader(f, delimiter=\"\\t\")\n for line in reader:\n label = line[\"country\"]\n labels.add(label)\n log(f\"Read {len(label_mapping)} from previous run.\")\n for label in tqdm(labels):\n if label not in label_mapping.keys():\n label = make_wikidata_not_cry(label)\n response = get_label_and_uri_from_wikidata_for_label_and_type(label, entity_uri)\n result = extract_bindings_or_empty_list(response)\n if len(result):\n for r in result:\n tmp = label_mapping.get(label, [])\n tmp.append(r[\"uri\"][\"value\"])\n label_mapping[label] = tmp\n else:\n\n if response.status_code != 200:\n tqdm.write(f\"[WARNING] No {entity_label} result for {label}, reason {response}.\")\n else:\n tqdm.write(f\"[INFO] No {entity_label} result for {label}.\")\n with open(entity_file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(f\"{entity_label};uri;label\\n\")\n for label, uris in label_mapping.items():\n for uri in uris:\n f.write(f\"{label};{uri};{entity_label}\\n\")\n\n\ndef annotate_speech_country2(graph):\n country_annotation_file = COUNTRY_MAPPING\n entity_label = \"Country\"\n uri = \"http://www.wikidata.org/entity/Q6256\"\n if not Path(country_annotation_file).is_file():\n make_entites_csv(country_annotation_file, uri, entity_label)\n batch_add_from_file_to_db_with_entity_label(graph, country_annotation_file, entity_label)\n log(\"Done.\")\n\n\ndef batch_add_from_file_to_db_with_entity_label(graph, annotation_file, entity_label):\n log(f\"Annotating {entity_label} label from {annotation_file}..\")\n query = f\"\"\"\n LOAD CSV WITH HEADERS FROM 'file:///{annotation_file}' AS row\n FIELDTERMINATOR \";\"\n MATCH (e:Institution {{name : row.{entity_label}}})\n SET e:{entity_label}\n MERGE (w:WDConcept {{uri : row.uri}})\n MERGE (w)-[:owl_sameAs]->(e)\n MERGE (w)<-[:owl_sameAs]-(e)\n \"\"\"\n graph.execute_query(query)\n","repo_name":"glaserL/unsc-ne","sub_path":"unscne/ner.py","file_name":"ner.py","file_ext":"py","file_size_in_byte":21220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"37975743515","text":"import os\n\nfrom fabric.api import run, sudo, env, cd, local, prefix, put, lcd, settings\nfrom fabric.contrib.files import exists, sed\nfrom fabric.contrib.project import rsync_project\n\nenv.use_ssh_config = True\n\nuser = 'deploy'\nkb_dir = '/var/www/knowledgebase'\nproject_dir = '.'\ndist = 'debian'\nhost_count = len(env.hosts)\ntmp_dir = '/tmp/uluru-platform' + str(os.getpid())\n\ndef _set_user_dir():\n global dist,user,kb_dir\n with settings(warn_only=True):\n issue = run('id ubuntu').lower()\n if 'id: ubuntu' in issue:\n dist = 'debian'\n elif 'uid=' in issue:\n dist = 'ubuntu'\n user = 'ubuntu'\n kb_dir = '/mnt/avos/knowledgebase'\n\ndef _clean_local():\n local(\"rm -rf %s\" % (tmp_dir))\n\ndef _prepare_remote_dirs():\n _set_user_dir()\n if not exists(kb_dir):\n sudo('mkdir -p %s' % kb_dir)\n sudo('chown -R 755 %s' % kb_dir)\n sudo('chown %s %s' % (user, kb_dir))\n\ndef _prepare_local_knowledgebase(target, install=\"true\"):\n local(\"mkdir -p %s\" % tmp_dir)\n if install == \"true\":\n local(\"./gitbook.sh install && ./gitbook init\" )\n local(\"./gitbook.sh build\" )\n local(\"cp -rv _book/* %s\" % tmp_dir )\n\ndef deploy_knowledgebase(target=\"stage\", install=\"false\", prod='cn'):\n global host_count\n _set_user_dir()\n if (host_count == len(env.hosts)):\n _prepare_local_knowledgebase(target, install)\n\n _prepare_remote_dirs()\n rsync_project(local_dir=tmp_dir + '/',\n remote_dir=kb_dir,\n delete=True)\n host_count -= 1\n if (host_count == 0):\n _clean_local()\n","repo_name":"leancloud/knowhow","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"80"} +{"seq_id":"22946831970","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nfrom difflib import ndiff\n\nfrom bidding_rb.html_process import download_page_test, extract_table\nfrom bidding_rb.data import target_keywords, end_words, para_formats, \\\n fuzzy_keywords\nfrom bs4 import BeautifulSoup\nfrom logging import getLogger\nimport functools\n\nlogger = getLogger(__name__)\n\n# 去除·-\nzh_puctutaion = '"#$%&'*+,/:;<=>@[\]^_`{|}~⦅⦆「」、\\u3000、〃〈〉《》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏﹑﹔!?。。'\n# 去除-\nen_puctutaion = '!\"#$%&\\'*+,./:;<=>?@[\\\\]^_`{|}~' '`]\" \\n'\npuctutaion = zh_puctutaion + en_puctutaion\n\nRE_MAO = re.compile('[::]')\nRE_CLOSE_TAG = re.compile('[::](.*?)(。|\\n|;)', re.DOTALL)\n\n\nclass Pipeline:\n def __init__(self,\n target_keywords=target_keywords,\n end_words=end_words,\n para_formats=para_formats,\n fuzzy_keywords=fuzzy_keywords):\n self.target_keywords = target_keywords\n self.fuzzy_keywords = fuzzy_keywords\n self.end_words_regex = re.compile('|'.join(map(re.escape, end_words)))\n self.para_formats = para_formats\n self.re_puctutaion = re.compile('[{}]'.format(re.escape(puctutaion)))\n # 去除 年|日\n self.re_special = re.compile('关于|年度|月|结果|成交|变更|延期|流标|中选|公开|公示')\n self.re_num = re.compile(' *?\\d *?')\n\n def debug4url(self, url, page, title):\n if not page:\n page = download_page_test(url)\n bs = BeautifulSoup(page, 'lxml')\n tables = extract_table(page)\n results = []\n\n body = bs.get_text()\n results.extend(self.target_keywords_page(body))\n if not results:\n for table in tables:\n results.extend(self.target_keywords_table(table))\n\n if not results:\n results.extend(self.context_page(body))\n for table in tables:\n results.extend(self.context_table(table))\n\n if not results:\n results.extend(self.fuzzy_keywords_page(body))\n for table in tables:\n results.extend(self.fuzzy_keywords_table(table))\n\n if not results:\n results.extend(self.title_extract(bs, title))\n for result in results:\n result['text'] = self.clean(result['text'])\n results = [r for r in results if r['text'].strip()]\n results = self.drop_dup(results)\n return results\n\n def target_keywords_page(self, body):\n texts = []\n for target_keyword in self.target_keywords:\n flag, match_result = self.regex_match(target_keyword, body)\n if flag:\n span = match_result.span()\n last_n_char = body[span[0]:span[0] + 3]\n if not RE_MAO.findall(last_n_char) and not RE_MAO.findall(target_keyword): \n continue\n text = self.cut_close(body[span[1]:])[:25]\n # 防止把下一个实体也提取出来\n text = re.split('乙方|地址|代理|乙 方|名称|地点|成交|评标|地 址|年|监督|公司地址|(盖章)', text)[0]\n end_flag, text = self.cut_end(text)\n if end_flag:\n logger.info(\n f'target_keywords_page: {target_keyword} {text}')\n texts.append(text)\n\n result = [{\n 'text': cell,\n 'source': 'target_keywords_page'\n } for cell in texts]\n return result\n\n def target_keywords_table(self, table):\n\n target_cells = self.regrex_match_table(table, self.target_keywords)\n # 获取右侧或下侧单元格内容并判断是否包含结尾词,\n # 若不包含则优先获取右侧内容\n all_cells = []\n for cell in target_cells:\n cell = cell[:25]\n flag, cell = self.cut_end(cell)\n if flag:\n all_cells.append(cell)\n result = [{\n 'text': cell,\n 'source': 'target_keywords_table'\n } for cell in all_cells]\n return result\n\n def context_page(self, body):\n texts = self.match_para_formats(body)\n result = [{'text': cell, 'source': 'context_page'} for cell in texts]\n\n return result\n\n def context_table(self, table):\n texts = []\n for cells in table:\n for cell in cells:\n if not isinstance(cell, str):\n continue\n texts.extend(self.match_para_formats(cell))\n\n result = [{'text': cell, 'source': 'context_table'} for cell in texts]\n return result\n\n def match_para_formats(self, text):\n texts = []\n for para_format in self.para_formats:\n flag, match_result = self.regex_findall(para_format, text)\n if flag:\n for match_text in match_result:\n logger.info(\n f'match_para_formats: {para_format} {match_text}')\n texts.extend(self.get_diff(para_format, match_text))\n\n new_texts = []\n for text in texts:\n flag, text = self.cut_end(text)\n if flag:\n new_texts.append(text)\n return new_texts\n\n @staticmethod\n def get_diff(text1, text2):\n result = []\n word = ''\n for token in ndiff(text1, text2):\n if token.startswith('+'):\n word += token[-1]\n else:\n if word:\n result.append(word)\n word = ''\n return result\n\n def fuzzy_keywords_page(self, body):\n texts = []\n for fuzzy_keyword in self.fuzzy_keywords:\n flag, match_result = self.regex_match(fuzzy_keyword, body)\n if flag:\n span = match_result.span()\n last_n_char = body[span[0]:span[0] + 3]\n if not RE_MAO.findall(last_n_char):\n continue\n\n text = self.cut_close(body[span[1]:])\n end_flag, text = self.cut_end(text)\n if end_flag:\n texts.append(text)\n\n result = [{\n 'text': cell,\n 'source': 'fuzzy_keywords_page'\n } for cell in texts]\n return result\n\n def fuzzy_keywords_table(self, table):\n target_cells = self.regrex_match_table(table, self.fuzzy_keywords)\n # 获取右侧或下侧单元格内容并判断是否包含结尾词,\n # 若不包含则优先获取右侧内容\n all_cells = []\n for cell in target_cells:\n flag, cell = self.cut_end(cell)\n if flag:\n all_cells.append(cell)\n result = [{\n 'text': cell,\n 'source': 'fuzzy_keywords_table'\n } for cell in all_cells]\n return result\n\n def title_extract(self, bs, title_input):\n title = bs.find('h4')\n if title:\n title = title.text\n else:\n title = title_input\n \n result = []\n title = re.split('关于|年', title)[0]\n flag, text = self.cut_end(title[:20])\n if flag:\n if '政府' in text:\n return result\n result.append({'text': text, 'source': 'title'})\n return result\n\n def regrex_match_table(self, table, regrexs):\n '''\n 通过正则组合获取符合条件的cell的右边和下面的cell\n '''\n def check_end_words(cell):\n match_result = self.end_words_regex.search(cell)\n flag = bool(match_result)\n return flag\n\n def search_right_cell(i, j):\n right_cell = None\n if j + 1 < col_size:\n right_cell = table[i][j + 1]\n return right_cell\n\n def search_down_cell(i, j):\n down_cell = None\n if i + 1 < row_size:\n down_cell = table[i+1][j]\n return down_cell\n\n # 匹配精准关键词定位在表格内时,\n # 判断关键词所在单元格字数是否大于10个字符,则跳过该关键词\n match_ij = []\n row_size = len(table)\n col_size = len(table[0])\n for i, cells in enumerate(table):\n for j, cell in enumerate(cells):\n if not isinstance(cell, str):\n cell = str(cell)\n if len(cell) > 10:\n continue\n for regrex in regrexs:\n if self.regex_match(regrex, cell)[0]:\n logger.info(f'target_keywords_table: {regrex} {cell}')\n match_ij.append((i, j))\n\n # 获取右侧或下侧单元格内容并判断是否包含结尾词,\n # 若不包含则优先获取右侧内容\n target_cells = []\n for i, j in match_ij:\n cell = table[i][j]\n right_cell = search_right_cell(i, j)\n down_cell = search_down_cell(i, j)\n if right_cell:\n right_flag = check_end_words(right_cell)\n else:\n right_flag = False\n if down_cell:\n down_flag = check_end_words(down_cell)\n else:\n down_flag = False\n\n cells = []\n if right_flag:\n target_cells.append(right_cell)\n logger.info(\n f'target_keywords_table: {cell} right {right_cell}')\n if down_flag:\n target_cells.append(down_cell)\n logger.info(f'target_keywords_table: {cell} down {down_cell}')\n\n if not right_flag and not down_flag and right_cell:\n target_cells.append(right_cell)\n logger.info(\n f'target_keywords_table: {cell} right {right_cell}')\n return target_cells\n\n def regex_match(self, regex, text):\n result = re.compile(regex).search(text)\n flag = bool(result)\n return flag, result\n\n def regex_findall(self, regex, text):\n result = re.compile(regex).findall(text)\n flag = bool(result)\n return flag, result\n\n def cut_end(self, text):\n # 匹配开头至机构名的文本\n last_index = self.find_last_index(text, self.end_words_regex)\n if last_index + 1 <= len(text):\n if text[last_index] in '))':\n last_index += 1\n text = text[:last_index]\n match_result = self.end_words_regex.search(text)\n flag = bool(match_result)\n return flag, text\n\n # def cut_end(self, text, cut_len=-1):\n # match_result = self.end_words_regex.search(text)\n # flag = bool(match_result)\n # if len(text) > cut_len and flag:\n # span = match_result.span()\n # end = span[1]\n # text = text[:end]\n # flag = True\n # return flag, text\n\n def cut_close(self, text):\n # 匹配关键词后至停止符(换行、句号等)的文本\n match_result = RE_CLOSE_TAG.search(text)\n if match_result:\n span = match_result.span()\n end = span[1]\n text = text[:end - 1]\n return text\n\n def clean(self, text):\n text = text[self.find_last_index(text, self.re_puctutaion):]\n text = text[self.find_last_index(text, self.re_special):]\n text = text[self.find_last_index(text, self.re_num):]\n return text.strip()\n\n def find_last_index(self, text, regrex):\n index = 0\n result = list(regrex.finditer(text))\n if result:\n index = result[-1].span()[-1]\n for _ in result:\n span = _.span()\n target_text = text[span[0]: span[1]]\n if '公司' in target_text:\n index = span[1]\n if re.compile('|'.join(map(re.escape, [\n '分公司',\n '分行',\n '支队',\n '电信局'\n ]))).findall(target_text):\n index = span[1]\n return index\n \n def drop_dup(self, result):\n # 打分排序\n for _ in result:\n text = _['text']\n point = 0\n if text.startswith('为'):\n point -= 1\n if len(text) <= 5:\n point -= 1\n if '公司' in text:\n if text.endswith('公司'):\n point += 4\n else:\n point += 2\n _['score'] = point\n\n result.sort(key=lambda x: x.pop('score', 0), reverse=True)\n\n return result","repo_name":"dsppman/ETL","sub_path":"beetle_cracker/re_extract_cracker/bidding_rule/biddingrulebase/bidding_rb/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":12751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"32855506054","text":"#-*-coding:utf-8-*-\r\nimport os\r\nimport cv2\r\nimport sys\r\nimport json\r\n\r\nsys.path.append(os.getcwd())\r\n\r\nfrom sys_tools import cv2_tools\r\nbdd_dirs = \"E:\\\\sw_datasets\\\\adas_detection\\\\bdd100k\"\r\nimagedst_dirs = \"E:\\\\sw_datasets\\\\adas_detection\\\\images\"\r\nlabels_dirs = \"E:\\\\sw_datasets\\\\adas_detection\\\\labels\"\r\n\r\nlabel_lists = ['car', 'bus', 'person', 'bike', 'truck', 'motor', 'train', 'rider', 'traffic sign', 'traffic light']\r\n\r\ndef make_dirs(dir):\r\n if not os.path.exists(dir):\r\n os.makedirs(dir)\r\n\r\ndef json2txt(jsonname, dstlabelsname):\r\n inputfile = open(jsonname, \"rb\")\r\n outputfile = open(dstlabelsname, \"w\")\r\n fileJson = json.load(inputfile)\r\n field = fileJson[\"name\"]\r\n if \"bdd100k_\" + field == (dstlabelsname.split(\"\\\\\")[-1]).split(\".\")[0]:\r\n frame = fileJson[\"frames\"]\r\n objects = frame[0]['objects']\r\n for i in range(len(objects)):\r\n label_flag = objects[i]['category']\r\n if label_flag in label_lists:\r\n boxes = objects[i]['box2d']\r\n boxes_top_x = str(boxes[\"x1\"])\r\n boxes_top_y = str(boxes[\"y1\"])\r\n boxes_bot_x = str(boxes[\"x2\"])\r\n boxes_bot_y = str(boxes[\"y2\"])\r\n line_content = label_flag + \",\" + boxes_top_x + \",\" + boxes_top_y + \",\" + boxes_bot_x + \",\" + boxes_bot_y\r\n outputfile.write(line_content)\r\n outputfile.write(\"\\n\")\r\n\r\n\r\n\r\n \r\n #print(boxes)\r\n\r\n\r\n #fileJson.close()\r\n outputfile.close()\r\n\r\n\r\n\r\n\r\nfor roots, parents, images in os.walk(bdd_dirs):\r\n for imagefile in images:\r\n srcimagename = os.path.join(roots, imagefile)\r\n dirprefixs = srcimagename.split(\"\\\\\")[-2]\r\n if srcimagename.endswith(\"jpg\"):\r\n dstdirs = os.path.join(imagedst_dirs, dirprefixs)\r\n make_dirs(dstdirs)\r\n dstimagename = os.path.join(dstdirs, \"bdd100k_\" + imagefile)\r\n print(dstimagename)\r\n cv2_tools.rename(srcimagename, dstimagename)\r\n elif srcimagename.endswith(\"json\"):\r\n dstdirs = os.path.join(labels_dirs, dirprefixs)\r\n make_dirs(dstdirs)\r\n imageprefixs = imagefile.split(\".\")[0]\r\n dstlabelsname = os.path.join(dstdirs, \"bdd100k_\" + imageprefixs + \".txt\")\r\n print(dstlabelsname)\r\n json2txt(srcimagename, dstlabelsname)\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n ","repo_name":"HappyLearningML/python_project","sub_path":"datasets_tools/datascripts/convertBddjson2xml.py","file_name":"convertBddjson2xml.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16527625883","text":"currency = (\n (2.56, \"BYN\"),\n (63.76, \"RUB\"),\n (1.03, \"EUR\"),\n (36.85, \"UAN\"),\n (146.85, \"JPY\"),\n (1, 'USD'),\n)\n\n\nclass Translate:\n def translate(self, cleaned_data, context):\n count = cleaned_data['count']\n count_1 = cleaned_data['count_1']\n count_2 = cleaned_data['count_2']\n last_count = round(float(count_2) / float(count_1) * count, 2)\n\n self.render(count, count_1, count_2, last_count, context)\n\n def render(self, count, count_1, count_2, last_count, context):\n context.update({'cur_1': x[1] for x in currency if str(x[0]) == str(count_1)})\n context.update({'cur_2': x[1] for x in currency if str(x[0]) == str(count_2)})\n\n context.update(\n {\n 'count': count,\n 'count_1': count_1,\n 'count_2': count_2,\n 'last_count': last_count,\n }\n )\n","repo_name":"VladVladVladbot/currency_rate","sub_path":"cool/mango/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"21105317242","text":"import logging\nimport sys\n\nfrom enh_scripts.utils.utils import open_or_stdin\n\nHUMAN_CHROMS = [\"chr%s\" % i for i in range(1, 23)] + [\"chrX\", \"chrY\"]\n\nLOG_DEFAULT_FORMAT = \"%(asctime)s [%(levelname)s] - %(message)s\"\n\nLOG_LEVEL_MAP = {\n \"debug\": logging.DEBUG,\n \"info\": logging.INFO,\n \"warn\": logging.WARN,\n}\n\n\ndef add_logging_args(parser):\n parser.add_argument(\"--log_level\", choices=LOG_LEVEL_MAP.keys(), default='info')\n parser.add_argument(\"--log_file\")\n\n\ndef init_logger(args):\n logger = logging.getLogger()\n logger.setLevel(LOG_LEVEL_MAP[args.log_level])\n formatter = logging.Formatter(LOG_DEFAULT_FORMAT)\n if not args.log_file:\n handler = logging.StreamHandler(stream=sys.stdout)\n else:\n handler = logging.FileHandler(args.log_file)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n","repo_name":"soedinglab/SNPtarget","sub_path":"enh_scripts/enh_scripts/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26642531414","text":"import os\nfrom io import BytesIO\nfrom typing import List, Tuple\n\nimport aiohttp.web\nimport cv2 as cv\nimport mlflow\nimport mxnet as mx\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom app.modules.mtcnn_detector import MtcnnDetector\nfrom dotenv import load_dotenv\nfrom loguru import logger\nfrom torchvision import transforms\n\nload_dotenv()\n\nos.environ[\"MLFLOW_TRACKING_URI\"] = os.getenv(\"MLFLOW_TRACKING_URI\")\nos.environ[\"MLFLOW_S3_ENDPOINT_URL\"] = os.getenv(\"MLFLOW_S3_ENDPOINT_URL\")\nos.environ[\"AWS_ACCESS_KEY_ID\"] = os.getenv(\"AWS_ACCESS_KEY_ID\")\nos.environ[\"AWS_SECRET_ACCESS_KEY\"] = os.getenv(\"AWS_SECRET_ACCESS_KEY\")\nmlflow.set_tracking_uri(os.environ[\"MLFLOW_TRACKING_URI\"])\nroutes = aiohttp.web.RouteTableDef()\ndetector: MtcnnDetector = MtcnnDetector(\n model_folder=\"/app/app/modules/mtcnn_model\",\n ctx=mx.cpu(),\n num_worker=1,\n accurate_landmark=True,\n threshold=[0.7, 0.8, 0.9],\n)\n\nmodel = mlflow.pytorch.load_model(\n os.getenv(\"MODEL_PATH\"), map_location=torch.device(\"cpu\")\n)\nmodel.eval()\n\n\ndef bytes_encode_image(image: np.ndarray) -> bytes:\n return BytesIO(cv.imencode(\".jpg\", image)[1].tostring()).read()\n\n\ndef preprocess_image(img: bytes) -> np.ndarray:\n image: np.ndarray = np.asarray(bytearray(img), dtype=\"uint8\")\n image = cv.imdecode(image, cv.IMREAD_COLOR)\n return image\n\n\ntransform = transforms.Compose(\n [\n transforms.Resize([224, 224]),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n)\n\n\ndef prepare_image(image: np.ndarray) -> torch.Tensor:\n image: Image = Image.fromarray(image)\n tensor = transform(image)\n tensor = tensor.unsqueeze(0)\n return tensor\n\n\n@routes.post(\"/detect_image\")\nasync def detect_image(request: aiohttp.web.Request):\n \"\"\"\n метод, который получает картинку, находит на ней лица,\n определяет, если ли на каждом нвйденном лице маска и\n возвращает в ответ картинку с нарисованными bbox\n и метками класса возле каждого лица\n :param request: входные данные http запроса\n :type request: aiohttp.web.Request\n :return: image if success, else status code >= 400\n :rtype:\n \"\"\"\n reader = await request.multipart()\n\n image = await reader.next()\n if not image:\n return aiohttp.web.HTTPBadRequest(reason=\"Please provide image file.\")\n if image:\n img_content: bytes = await image.read()\n else:\n return {\"error:wrong image\"}, 400\n\n im: np.ndarray = preprocess_image(img_content)\n\n detection_result: List = detector.detect_face(im)\n for i in detection_result[0]:\n bbox: List = i\n bbox = [int(i) for i in bbox]\n bbox = [0 if i < 0 else i for i in bbox]\n croped_frame: np.ndarray = im[bbox[1] : bbox[3], bbox[0] : bbox[2]]\n\n image_tensor: torch.Tensor = prepare_image(croped_frame)\n result: torch.Tensor = model(image_tensor)\n logger.info(result)\n _, predicted = torch.max(result.data, 1)\n result: int = predicted.item()\n color: Tuple = ()\n text: str = \"\"\n if result == 1:\n color = (0, 0, 255)\n text = \"without_mask\"\n if result == 0:\n color = (0, 255, 0)\n text = \"with_mask\"\n cv.rectangle(im, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color, 5)\n cv.putText(\n im, text, (bbox[0], bbox[1] - 10), cv.FONT_HERSHEY_SIMPLEX, 0.9, color, 2\n )\n result_image: bytes = bytes_encode_image(im)\n return aiohttp.web.Response(body=result_image, content_type=\"image/jpeg\")\n","repo_name":"starminalush/mask_classification_deploy","sub_path":"api/backend/app/views/detect_masks.py","file_name":"detect_masks.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"39960651569","text":"def print_list(nums:list):\n #打印数组\n for i in range(len(nums)):\n print(str(nums[i]) + ' ',end='')\n print()\n\n\ndef do(A:list, B:list, k):\n result = []\n idxA = 0\n idxB = 0\n while True:\n if idxA == len(A):\n result.extend(B[idxB:])\n return result[k-1]\n elif idxB == len(B):\n result.extend(A[idxA:])\n return result[k-1]\n else:\n if A[idxA] < B[idxB]:\n tmp = A[idxA]\n result.append(tmp)\n idxA += 1\n else:\n tmp = B[idxB]\n result.append(tmp)\n idxB += 1\n\n\n\nT = int(input())\nfor t in range(T):\n input1 = input().split(' ')\n sizeA = int(input1[0])\n sizeB = int(input1[1])\n k = int(input1[2])\n A = [int(x) for x in input().split(' ')]\n B = [int(x) for x in input().split(' ')]\n print(do(A,B,k))\n\n\n\n\n\n\n\n","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2467/60775/274897.py","file_name":"274897.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"71468824578","text":"# with open(\"my_file.txt\") as file:\n# contents = file.read()\n# print(contents)\n\n# with open(\"new_file.txt\", \"a\") as file:\n# file.write(\"\\ntesting\")\n\nPLACEHOLDER = \"[name]\"\n\nwith open(\"invited_names.txt\") as names_file:\n names = names_file.readlines()\n print(names)\n\nwith open(\"starting_letter.txt\") as letter_file:\n letter_contents = letter_file.read()\n for name in names:\n stripped_name = name.strip()\n new_letter = letter_contents.replace(PLACEHOLDER, stripped_name)\n with open(f\"{stripped_name}_output.txt\", \"w\") as output_letter:\n output_letter.write(new_letter)","repo_name":"ardenor/100daysPython","sub_path":"day24/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"70707635779","text":"#!/usr/bin/python3\nimport time\nimport serial\n\nprint(\"UART Demonstration Program\")\nprint(\"Raspberry Pi4 Server\")\n\ndef serial_server(server_port, path, q):\n # Wait a second to let the port initialize\n try:\n while True:\n if server_port.inWaiting() > 0:\n\n # serial readlines\n data = server_port.readline()\n\n with open(path, 'a') as f:\n f.write(data)\n\n q.append(1)\n # print(data)\n # server_port.write(data)\n #\n # if data == \"\\r\".encode():\n # # For Windows boxen on the other end\n # server_port.write(\"\\n\".encode())\n\n\n except KeyboardInterrupt:\n print(\"Exiting Program\")\n\n except Exception as exception_error:\n print(\"Error occurred. Exiting Program\")\n print(\"Error: \" + str(exception_error))\n\n finally:\n server_port.close()\n pass\n\nif __name__ == \"__main__\":\n server_port = serial.Serial(\n port=\"/dev/ttyS0\",\n baudrate=9600,\n bytesize=serial.EIGHTBITS,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n )","repo_name":"Jarvis-Geun/2022ESWContest_mobility_6067","sub_path":"inference/Raspberry/serial_server.py","file_name":"serial_server.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"80"} +{"seq_id":"10395335011","text":"import numpy as np\nimport nltk\nimport pandas as pd\nimport random\nimport json\nimport pickle\nimport random\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPClassifier\nimport joblib\n\nnltk.download ('punkt')\nnltk.download ('wordnet')\nnltk.download ('omw-1.4')\n\nlemmatizer = WordNetLemmatizer()\nraw_doc = json.loads(open('ProBot_DataSet.json').read())\n\nwords = []\nclasses = []\ndocuments = []\nignore_let = ['?', '!', \",\", \".\"]\n\nfor intent in raw_doc['intents']:\n for pat in intent['patterns']:\n word_list = nltk.word_tokenize(pat)\n words.extend(word_list)\n documents.append((word_list, intent['tag']))\n if intent['tag'] not in classes:\n classes.append(intent['tag'])\n\nwords = [lemmatizer.lemmatize(word.lower()) for word in words if word not in ignore_let]\nwords = sorted(set(words))\nclasses = sorted(set(classes))\n\npickle.dump(words, open('words.pkl', 'wb'))\npickle.dump(classes, open('classes.pkl', 'wb'))\n\ntrain = []\noutput_emp = [0] * len(classes)\nfor doc in documents:\n bag = []\n word_pat = doc[0]\n word_pat = [lemmatizer.lemmatize(word.lower()) for word in word_pat]\n for word in words:\n bag.append(1) if word in word_pat else bag.append(0)\n out_row = list(output_emp)\n out_row[classes.index(doc[1])] = 1\n train.append([bag, out_row])\n\nrandom.shuffle(train)\ntrain = np.array(train, dtype=object)\n\ntrain_x = list(train[:, 0])\ntrain_y = list(train[:, 1])\nt_x, test_x, t_y, test_y = train_test_split(train_x, train_y, test_size=0.2, random_state=42)\n\n\nmodel = MLPClassifier(hidden_layer_sizes=(256, 128, 64), max_iter=500, activation='relu', solver='adam', random_state=42)\nmodel.fit(train_x, train_y)\n\njoblib.dump(model, 'chatbot_model.pkl')\nprint(\"Done\")","repo_name":"Ashad001/ProBot-A-voice-controlled-chatbot","sub_path":"TRAINING/ProBot_Training.py","file_name":"ProBot_Training.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"43456314725","text":"import torch\nimport falcor\nimport numpy as np\n\nEPS = 1e-10\n\n\ndef dot(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n return torch.sum(x * y, dim=-1, keepdim=True)\n\n\ndef length(x: torch.Tensor) -> torch.Tensor:\n return torch.sqrt(dot(x, x))\n\n\ndef length_safe(x: torch.Tensor, eps: float = EPS) -> torch.Tensor:\n return torch.sqrt(torch.clamp(dot(x, x), min=eps*eps)) # Clamp to avoid NaN gradients because grad(sqrt(0)) = NaN.\n\n\ndef normalize_safe(x: torch.Tensor, eps: float = EPS) -> torch.Tensor:\n return x / length_safe(x, eps)\n\n\nclass Mesh:\n def __init__(\n self,\n tri_idx=None,\n v_pos=None,\n v_norm=None,\n v_tangent=None,\n v_texcrd=None,\n ):\n self.tri_idx = tri_idx\n self.v_pos = v_pos\n self.v_norm = v_norm\n self.v_tangent = v_tangent\n self.v_texcrd = v_texcrd\n\n self.buffers = {\n \"triangleIndices\": None,\n \"positions\": None,\n \"normals\": None,\n \"tangents\": None,\n \"texcrds\": None,\n }\n\n def init_falcor(\n self,\n device: falcor.Device,\n scene: falcor.Scene,\n vertex_count: int,\n triangle_count: int,\n ):\n for key in self.buffers:\n elem_count = triangle_count if key == \"triangleIndices\" else vertex_count\n if (\n self.buffers[key] is None\n or self.buffers[key].element_count < elem_count\n ):\n self.buffers[key] = device.create_structured_buffer(\n struct_size=12,\n element_count=elem_count,\n bind_flags=falcor.ResourceBindFlags.ShaderResource\n | falcor.ResourceBindFlags.UnorderedAccess\n | falcor.ResourceBindFlags.Shared,\n )\n\n def load_from_falcor(self, testbed: falcor.Testbed, mesh_id: int):\n scene = testbed.scene\n device = testbed.device\n mesh = scene.get_mesh(mesh_id)\n\n self.init_falcor(\n device, scene, mesh.vertex_count, mesh.triangle_count\n )\n scene.get_mesh_vertices_and_indices(mesh_id, self.buffers)\n\n # Copy from Falcor to PyTorch.\n self.tri_idx = torch.zeros([mesh.triangle_count, 3], dtype=torch.int32)\n self.buffers[\"triangleIndices\"].copy_to_torch(self.tri_idx)\n\n self.v_pos = torch.zeros([mesh.vertex_count, 3], dtype=torch.float32)\n self.buffers[\"positions\"].copy_to_torch(self.v_pos)\n\n self.v_texcrd = torch.zeros([mesh.vertex_count, 3], dtype=torch.float32)\n self.buffers[\"texcrds\"].copy_to_torch(self.v_texcrd)\n\n device.render_context.wait_for_cuda()\n\n def update_to_falcor(self, testbed: falcor.Testbed, mesh_id: int):\n scene = testbed.scene\n device = testbed.device\n\n # Copy from PyTorch to Falcor.\n self.buffers[\"positions\"].from_torch(self.v_pos.detach())\n self.buffers[\"normals\"].from_torch(self.v_norm.detach())\n self.buffers[\"tangents\"].from_torch(self.v_tangent.detach())\n self.buffers[\"texcrds\"].from_torch(self.v_texcrd.detach())\n device.render_context.wait_for_cuda()\n\n # Bind shader data.\n scene.set_mesh_vertices(mesh_id, self.buffers)\n\n def compute_shading_frame(self):\n self.compute_normals()\n self.compute_tangents()\n\n # From nvdiffrec.\n # Compute smooth vertex normals.\n def compute_normals(self):\n idx = [\n self.tri_idx[:, 0].type(torch.int64),\n self.tri_idx[:, 1].type(torch.int64),\n self.tri_idx[:, 2].type(torch.int64),\n ]\n pos = [self.v_pos[idx[0], :], self.v_pos[idx[1], :], self.v_pos[idx[2], :]]\n face_normals = torch.cross(pos[1] - pos[0], pos[2] - pos[0])\n\n # Splat face normals to vertices.\n v_normals = torch.zeros_like(self.v_pos)\n v_normals.scatter_add_(0, idx[0][:, None].repeat(1, 3), face_normals)\n v_normals.scatter_add_(0, idx[1][:, None].repeat(1, 3), face_normals)\n v_normals.scatter_add_(0, idx[2][:, None].repeat(1, 3), face_normals)\n\n # Normalize, replace zero (degenerated) normals with some default value.\n v_normals = torch.where(\n length(v_normals) > EPS,\n v_normals,\n torch.tensor([0.0, 0.0, 1.0], dtype=torch.float32, device=\"cuda\"),\n )\n v_normals = normalize_safe(v_normals)\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(v_normals))\n\n self.v_norm = v_normals\n\n # From nvdiffrec.\n # Compute tangent space from texture map coordinates.\n # Follows http://www.mikktspace.com/ conventions.\n def compute_tangents(self):\n idx = [\n self.tri_idx[:, 0].type(torch.int64),\n self.tri_idx[:, 1].type(torch.int64),\n self.tri_idx[:, 2].type(torch.int64),\n ]\n pos = [self.v_pos[idx[0], :], self.v_pos[idx[1], :], self.v_pos[idx[2], :]]\n texcrd = [\n self.v_texcrd[idx[0], :],\n self.v_texcrd[idx[1], :],\n self.v_texcrd[idx[2], :],\n ]\n\n v_tangents = torch.zeros_like(self.v_norm)\n\n # Compute tangent space for each triangle.\n uve1 = texcrd[1] - texcrd[0]\n uve2 = texcrd[2] - texcrd[0]\n pe1 = pos[1] - pos[0]\n pe2 = pos[2] - pos[0]\n\n nom = pe1 * uve2[:, 1:2] - pe2 * uve1[:, 1:2]\n denom = uve1[:, 0:1] * uve2[:, 1:2] - uve1[:, 1:2] * uve2[:, 0:1]\n\n # Avoid division by zerofor degenerated texture coordinates.\n tang = nom / torch.where(\n denom > 0.0, torch.clamp(denom, min=EPS), torch.clamp(denom, max=-EPS)\n )\n\n # Update all 3 vertices.\n for i in range(3):\n t_idx = idx[i][:, None].repeat(1, 3)\n v_tangents.scatter_add_(0, t_idx, tang)\n\n # Normalize, replace zero (degenerated) tangents with some default value.\n default_tangents = torch.where(\n dot(\n self.v_norm,\n torch.tensor([1.0, 0.0, 0.0], dtype=torch.float32, device=\"cuda\"),\n )\n > 0.9999,\n torch.tensor([0.0, 1.0, 0.0], dtype=torch.float32, device=\"cuda\"),\n torch.tensor([1.0, 0.0, 0.0], dtype=torch.float32, device=\"cuda\"),\n )\n v_tangents = torch.where(length(v_tangents) > EPS, v_tangents, default_tangents)\n v_tangents = normalize_safe(v_tangents)\n\n # Make sure tangent is orthogonal to normal.\n v_tangents = normalize_safe(\n v_tangents - self.v_norm * dot(self.v_norm, v_tangents)\n )\n\n if torch.is_anomaly_enabled():\n assert torch.all(torch.isfinite(v_tangents))\n\n self.v_tangent = v_tangents\n","repo_name":"NVIDIAGameWorks/Falcor","sub_path":"scripts/inv-rendering/mesh_utils.py","file_name":"mesh_utils.py","file_ext":"py","file_size_in_byte":6741,"program_lang":"python","lang":"en","doc_type":"code","stars":2197,"dataset":"github-code","pt":"80"} +{"seq_id":"44376916115","text":"# develop an mlp for blobs dataset\nfrom sklearn.datasets import make_blobs\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom matplotlib import pyplot\n\nX, y = make_blobs(n_samples=1100, centers=3, n_features=2, cluster_std=2, random_state=2) # generate 2d classification dataset\ny = to_categorical(y) # one hot encode output variable\n\n# split into train and test\nn_train = 100\ntrainX, testX = X[:n_train, :], X[n_train:, :]\ntrainy, testy = y[:n_train], y[n_train:]\nprint(trainX.shape, testX.shape)\n\n# define model\nmodel = Sequential()\nmodel.add(Dense(25, input_dim=2, activation='relu'))\nmodel.add(Dense(3, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nhistory = model.fit(trainX, trainy, validation_data=(testX, testy), epochs=500, verbose=0) # fit model\n\n# evaluate the model\n_, train_acc = model.evaluate(trainX, trainy, verbose=0)\n_, test_acc = model.evaluate(testX, testy, verbose=0)\nprint('Train: %.3f, Test: %.3f' % (train_acc, test_acc))\n\n# learning curves of model accuracy\npyplot.plot(history.history['accuracy'], label='train')\npyplot.plot(history.history['val_accuracy'], label='test')\npyplot.legend()\npyplot.show()","repo_name":"m-ahmadi/exref","sub_path":"ml/tf/net - stacking/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"80"} +{"seq_id":"5823400254","text":"__author__ = \"Viv Sedov\"\n__email__ = \"viv.sb@hotmail.com\"\n\nimport numpy as np\nfrom frosch import hook\n\n\"\"\"\nFor this case we have, \nn_neurons is the next output of neurons that we have\nn_inputs is the length of how ever many inputs we get \n\n\nso for the next given value the inputs would allways be the n_neurons \n\n\"\"\"\n\n\nclass Dense_Layer:\n def __init__(self, n_inputs: int, n_neurons: int):\n self.weights = 0.10 * np.random.randn(\n n_inputs, n_neurons\n ) # This is just random generated results\n self.biases = np.zeros((1, n_neurons))\n\n def forall(self, inputs: list) -> np:\n self.outputs = np.dot(inputs, self.weights) + self.biases\n\n\nclass With_Weights:\n def __init__(self, weights: list):\n self.weights = np.array(weights).T\n self.biases = np.zeros(\n (1, len(self.weights[0]))\n ) # In this case we woudl force this\n\n def forward(self, inputs: list) -> np:\n self.outputs = np.dot(inputs, self.weights) + self.biases\n\n\ndef main() -> np:\n\n X = [\n [0.2, 0.8, -0.5, 1.0],\n [0.5, -0.91, 0.26, -0.5],\n [-0.26, -0.27, 0.17, 0.87],\n ] # Input data is always an X\n\n W_1 = [\n [0.2, 0.8, -0.5, 1.0],\n [0.5, -0.91, 0.26, -0.5],\n [-0.26, -0.27, 0.17, 0.87],\n ]\n # As some infomation, most times you dont really hold the weights in an arr\n\n layer_withWeights = With_Weights(W_1)\n layer_withWeights.forward(X)\n\n print(layer_withWeights.outputs)\n\n # This would be continue onwards, with what ever values that you had .\n\n\n# x = 10 # This can be any other value or number that you want\n# layer_1 = Dense_Layer(4, x)\n\n# layer_1.forall(X)\n# # print(layer_1.outputs)\n\n# layer_2 = Dense_Layer(x, 2) # This has to be what ever it had before\n\n# layer_2.forall(layer_1.outputs)\n# print(layer_2.outputs)\n\n\nif __name__ == \"__main__\":\n # hook(theme=\"fruity\")\n main()\n","repo_name":"vsedov/NeuralNetworks","sub_path":"Main/NeuralNetworkClass.py","file_name":"NeuralNetworkClass.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"4791949427","text":"import os\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nfilepath = os.path.dirname(__file__)\n\ndef options():\n chrome_options = Options()\n chrome_options.add_experimental_option('prefs', {\n \"download.default_directory\": f'{filepath}/venta/pdf_file',\n \"download.prompt_for_download\": False,\n \"download.directory_upgrade\": True,\n \"plugins.always_open_pdf_externally\": True\n })\n\n return chrome_options\n\ndef wd():\n chrome_driver = f'{filepath}/chromedriver'\n driver = webdriver.Chrome(options=options(), executable_path=chrome_driver)\n driver.implicitly_wait(10)\n return driver\n","repo_name":"trangtruong1610/web-selenium","sub_path":"webdriver.py","file_name":"webdriver.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"20327681189","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 19 20:30:56 2018\n\n@author: yoshiki\n\"\"\"\n\nimport pandas as pd\nfrom pyecharts import Pie,Line,Scatter\nimport os \nimport numpy as np\nimport jieba\nimport jieba.analyse\nfrom wordcloud import WordCloud,ImageColorGenerator\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n \nfont = FontProperties(fname=r'c:\\windows\\fonts\\simsun.ttc')#,size=20指定本机的汉字字体位置\n\nos.chdir('F:\\\\python_study\\\\pachong\\\\工作细胞')\n\ndatas = pd.read_csv('gzxb20181019.csv',index_col = 0,encoding = 'gbk')\n\n\n\"\"\"\n描述性分析\n\"\"\"\n\n\ndel datas['ctime']\ndel datas['cursor']\ndel datas['liked']\n# 评分\n\nscores = datas.score.groupby(datas['score']).count()\npie1 = Pie(\"评分\", title_pos='center', width=900)\npie1.add(\n \"评分\",\n ['一星','二星','三星','四星','五星'],\n scores.values,\n radius=[40, 75],\n# center=[50, 50],\n is_random=True,\n# radius=[30, 75],\n is_legend_show=False,\n is_label_show=True,\n)\npie1.render('评分.html')\n\n\n\ndatas['dates'] = datas.date.apply(lambda x:pd.Timestamp(x).date())\ndatas['time'] = datas.date.apply(lambda x:pd.Timestamp(x).time().hour)\n\n\nnum_date = datas.author.groupby(datas['dates']).count()\n\n# 评论数时间分布\nchart = Line(\"评论数时间分布\")\nchart.use_theme('dark')\nchart.add( '评论数时间分布',num_date.index, num_date.values, is_fill=True, line_opacity=0.2,\n area_opacity=0.4, symbol=None)\n\nchart.render('评论时间分布.html')\n\n# 好评字数分布\ndatalikes = datas.loc[datas.likes>5]\ndatalikes['num'] = datalikes.content.apply(lambda x:len(x))\nchart = Scatter(\"likes\")\nchart.use_theme('dark')\nchart.add('likes', np.log(datalikes.likes), datalikes.num, is_visualmap=True,\n xaxis_name = 'log(评论字数)',\n \n )\nchart.render('好评字数分布.html')\n\n\n\n\n\n\n# 评论每日内的时间分布\nnum_time = datas.author.groupby(datas['time']).count()\n\n# 时间分布\n\nchart = Line(\"评论日内时间分布\")\nchart.use_theme('dark')\nchart.add(\"评论数\", x_axis = num_time.index.values,y_axis = num_time.values,\n is_label_show=True,\n mark_point_symbol='diamond', mark_point_textcolor='#40ff27',\n line_width = 2\n )\n\nchart.render('评论日内时间分布.html')\n\n\n# 时间分布\nchart = Line(\"评论数时间分布\")\nchart.use_theme('dark')\nchart.add( '评论数时间分布',num_date.index, num_date.values, is_fill=True, line_opacity=0.2,\n area_opacity=0.4, symbol=None)\n\nchart.render('评论时间分布.html')\n\n# 评分时间分布\ndatascore = datas.score.groupby(datas.dates).mean()\nchart = Line(\"评分时间分布\")\nchart.use_theme('dark')\nchart.add('评分', datascore.index, \n datascore.values, \n line_width = 2 \n )\nchart.render('评分时间分布.html')\n\n\n\"\"\"\n评论分析\n\"\"\"\n\ntexts = ';'.join(datas.content.tolist())\ncut_text = \" \".join(jieba.cut(texts))\n# TF_IDF\nkeywords = jieba.analyse.extract_tags(cut_text, topK=500, withWeight=True, allowPOS=('a','e','n','nr','ns'))\ntext_cloud = dict(keywords)\npd.DataFrame(keywords).to_excel('TF_IDF关键词前500.xlsx')\n\n\n\n\nbg = plt.imread(\"血小板.jpg\")\n# 生成\nwc = WordCloud(# FFFAE3\n background_color=\"white\", # 设置背景为白色,默认为黑色\n width=400, # 设置图片的宽度\n height=600, # 设置图片的高度\n mask=bg,\n random_state = 2,\n max_font_size=500, # 显示的最大的字体大小\n font_path=\"STSONG.TTF\", \n).generate_from_frequencies(text_cloud)\n# 为图片设置字体\n\n# 图片背景\n#bg_color = ImageColorGenerator(bg)\n#plt.imshow(wc.recolor(color_func=bg_color))\nplt.imshow(wc)\n# 为云图去掉坐标轴\nplt.axis(\"off\")\nplt.show()\nwc.to_file(\"词云.png\")\n\n\n\n \n","repo_name":"OneTeam1912/Data_analysis_Cells_At_Work","sub_path":"data_analyse.py","file_name":"data_analyse.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"20990782240","text":"import argparse\nimport os\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom lrschedualer import load_schedualers\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom network import ImplicitNet\nfrom datasets import collate_fn\nfrom utils import import_class, load_config, make_backups\nfrom torch.utils.tensorboard import SummaryWriter\n\nclass Trainer(object):\n def __init__(\n self,\n out_path,\n device: torch.device = torch.device('cpu'),\n lrschedual: list = None,\n ckpt_freq: int = -1,\n epoch_begin: int = 0,\n num_epochs: int = 1,\n mini_batch: int = 1\n ) -> None:\n super().__init__()\n self.out_path = out_path\n self.num_epochs = num_epochs\n self.ckpt_freq = ckpt_freq\n self.device = device\n self.epoch_begin = epoch_begin\n self.lrschedual = lrschedual\n self.mini_batch = mini_batch\n self.logger = SummaryWriter(os.path.join(out_path, 'logs'))\n self.scaler = torch.cuda.amp.GradScaler()\n\n def update_lr(self, optim, n_epoch, pbar):\n '''update learning rate from the provided schedualers\n '''\n if self.lrschedual is None:\n return\n\n model_schedualer = self.lrschedual.get(\"model\")\n latent_schedualer = self.lrschedual.get(\"latent\")\n\n if model_schedualer is not None:\n last_lr_model = optim.param_groups[0]['lr']\n new_lr_model = model_schedualer.get_lr(n_epoch)\n if last_lr_model != new_lr_model:\n optim.param_groups[0]['lr'] = new_lr_model\n pbar.write(\"model lr is set to {}\".format(new_lr_model))\n\n if latent_schedualer is not None:\n new_lr_latent = latent_schedualer.get_lr(n_epoch)\n last_lr_latent = optim.param_groups[1]['lr']\n if last_lr_latent != new_lr_latent:\n optim.param_groups[1]['lr'] = new_lr_latent\n pbar.write(\"latent lr is set to {}\".format(new_lr_latent))\n\n def fit(\n self,\n model: torch.nn.Module,\n data_loader: DataLoader,\n optim_ckpt: str = None\n ) -> None:\n '''train/optimise a network/latents\n Args:\n model (moduel): initialized network,\n data_loader (DataLoader): train/eval data loader\n optim_ckpt (str): ckpt path to the optimizer (if any)\n '''\n # model.train()\n step_global = 0\n optimizer = model.configure_optimizers(ckpt=optim_ckpt)\n for n_epoch in range(self.epoch_begin, self.num_epochs):\n batch_loss = 0\n sdf_loss = 0\n latent_loss = 0\n # self.pbar = tqdm(data_loader)\n pbar = tqdm(total=len(data_loader)*self.mini_batch)\n self.update_lr(optimizer, n_epoch, pbar)\n\n num_batch_step = 0\n for n_batch, batch_data in enumerate(data_loader):\n batch_data = batch_data.view(-1, 6)\n batch_data = batch_data[torch.randperm(batch_data.shape[0]), :]\n chunk_data = torch.chunk(batch_data, self.mini_batch)\n\n for n_chunk in range(len(chunk_data)):\n mini_batch_data = chunk_data[n_chunk].to(self.device)\n\n with torch.cuda.amp.autocast():\n losses = model.training_step(\n mini_batch_data, n_epoch)\n\n loss = losses['loss']\n\n optimizer.zero_grad()\n self.scaler.scale(loss).backward()\n self.scaler.step(optimizer)\n self.scaler.update()\n\n batch_loss += loss.item()\n sdf_loss += losses['sdf_loss']\n latent_loss += losses['latent_loss']\n step_global += 1\n num_batch_step += 1\n\n pbar.set_description(\n \"Epoch {} loss: {:.4f} sdf: {:.4f} latent: {:.4f}\".format(\n n_epoch,\n batch_loss/num_batch_step,\n sdf_loss/num_batch_step,\n latent_loss/num_batch_step\n )\n )\n\n pbar.update(1)\n self.logger.add_scalar(\n 'train/loss', loss.item(), step_global)\n self.logger.add_scalar(\n 'train/sdf_loss', losses['sdf_loss'], step_global)\n self.logger.add_scalar(\n 'train/latent_loss', losses['latent_loss'], step_global)\n\n if (n_epoch > 0 and self.ckpt_freq > 0):\n if n_epoch % self.ckpt_freq == 0:\n self.save_ckpt(model, optim=optimizer, epoch=n_epoch)\n self.save_latest(model, optim=optimizer, epoch=n_epoch)\n\n def save_ckpt(self, model, optim=None, epoch=0):\n model.save_ckpt(os.path.join(\n self.out_path, 'ckpt_e{}_model.pth'.format(epoch)), optim, epoch)\n model.save_latents(os.path.join(\n self.out_path, 'ckpt_e{}_latents.npy'.format(epoch)), epoch)\n\n def save_latest(self, model, optim=None, epoch=0):\n model.save_ckpt(os.path.join(\n self.out_path, 'latest_model.pth'), optim, epoch)\n model.save_latents(os.path.join(\n self.out_path, 'latest_latents.npy'), epoch)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('data')\n parser.add_argument('out_path')\n parser.add_argument('--ckpt', type=str, default=None)\n parser.add_argument('--latents', type=str, default=None)\n parser.add_argument('--cfg', type=str, default='configs/basic.json')\n parser.add_argument('--threads', type=int, default=12)\n parser.add_argument('--mini_batch', type=int, default=1)\n parser.add_argument('--cpu', action='store_true')\n parser.add_argument('--orient', action='store_true')\n parser.add_argument('--load_optim', action='store_true')\n parser.add_argument('--reset_epoch', action='store_true')\n args = parser.parse_args()\n\n # backup arch and config\n # make_backups(args.out_path, cfg_name=args.cfg)\n\n device = torch.device('cpu' if args.cpu else 'cuda')\n train_cfg = load_config(args.cfg)[\"train\"]\n\n # load training data\n DatasetName = import_class('datasets.'+train_cfg[\"dataset\"][\"name\"])\n train_data = DatasetName(\n args.data, args.orient,\n **train_cfg[\"dataset\"][\"args\"])\n train_loader = DataLoader(\n train_data,\n batch_size=train_cfg[\"batch_size\"],\n num_workers=args.threads,\n shuffle=True,\n collate_fn=collate_fn)\n\n # load model arch and (optionally) ckpts\n model, epoch = ImplicitNet.create_from_cfg(\n args.cfg, ckpt=args.ckpt, device=device)\n\n # initialize latent vecs and (optionally) load from ckpts\n model.initialize_latents(\n train_data.num_latents,\n ckpt=args.latents, device=device)\n model.train()\n\n trainer = Trainer(\n device=device,\n out_path=args.out_path,\n epoch_begin=0 if args.reset_epoch else epoch,\n lrschedual=load_schedualers(train_cfg[\"schedualers\"]),\n ckpt_freq=train_cfg[\"ckpt_frequency\"],\n num_epochs=train_cfg[\"num_epoch\"],\n mini_batch=train_cfg[\"mini_batch\"]\n )\n\n trainer.fit(\n model, train_loader,\n optim_ckpt=args.ckpt if args.load_optim else None)\n\n # final saves\n model.save_ckpt(\n os.path.join(args.out_path, 'last_ckpt.pth'))\n model.save_latents(\n os.path.join(args.out_path, 'last_latents.npy'))\n","repo_name":"xingruiy/ImplicitReg","sub_path":"traininig/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":7698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"14677570262","text":"# GCD : 유클리드 알고리즘. 최대공약수 문제\n\ndef gcd(a, b):\n a, b = max(a, b), min(a, b)\n c = 1\n while c > 0:\n c = a % b\n a, b = b, c\n\n return a\n\n\nn = int(input())\n\nfor _ in range(n):\n answer = 0\n t = list(map(int, input().split()))\n\n for i in range(1, len(t)):\n a = t[i]\n while i < len(t):\n i += 1\n\n if i == len(t):\n break\n else:\n answer += gcd(a, t[i])\n\n print(answer)\n","repo_name":"Scope0204/Programmers_Practice","sub_path":"baekjoon/9613_GCD.py","file_name":"9613_GCD.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"21828219727","text":"from __future__ import annotations\n\nimport logging\n\nfrom xia2.Driver.DriverFactory import DriverFactory\n\nlogger = logging.getLogger(\"xia2.Wrappers.Dials.Merge\")\n\n\ndef DialsMerge(DriverType=None):\n \"\"\"A factory for DialsMergeWrapper classes.\"\"\"\n\n DriverInstance = DriverFactory.Driver(DriverType)\n\n class DialsMergeWrapper(DriverInstance.__class__):\n \"\"\"A wrapper for dials.merge\"\"\"\n\n def __init__(self):\n # generic things\n super().__init__()\n\n self.set_executable(\"dials.merge\")\n\n # clear all the header junk\n self.reset()\n\n self._experiments_filename = None\n self._reflections_filename = None\n self._mtz_filename = None\n self._truncate = False\n self._html_report = None\n self._project_name = None\n self._crystal_names = None\n self._dataset_names = None\n self._partiality_threshold = None\n\n def set_partiality_threshold(self, v):\n self._partiality_threshold = v\n\n def set_project_name(self, name):\n self._project_name = name\n\n def set_crystal_names(self, names):\n self._crystal_names = names\n\n def set_dataset_names(self, names):\n self._dataset_names = names\n\n def set_experiments_filename(self, experiments_filename):\n self._experiments_filename = experiments_filename\n\n def get_experiments_filename(self):\n return self._experiments_filename\n\n def set_reflections_filename(self, reflections_filename):\n self._reflections_filename = reflections_filename\n\n def get_reflections_filename(self):\n return self._reflections_filename\n\n def set_mtz_filename(self, filename):\n self._mtz_filename = filename\n\n def get_mtz_filename(self):\n return self._mtz_filename\n\n def set_html_report(self, filename):\n self._html_report = filename\n\n def run(self):\n \"\"\"Run dials.merge\"\"\"\n self.clear_command_line()\n\n assert self._experiments_filename\n assert self._reflections_filename\n self.add_command_line(self._reflections_filename)\n self.add_command_line(self._experiments_filename)\n\n self.add_command_line(\"truncate=%s\" % self._truncate)\n\n if self._mtz_filename:\n self.add_command_line(\"output.mtz=%s\" % self._mtz_filename)\n\n if self._project_name:\n self.add_command_line(\"output.project_name=%s\" % self._project_name)\n if self._crystal_names:\n self.add_command_line(\"output.crystal_names=%s\" % self._crystal_names)\n if self._dataset_names:\n self.add_command_line(\"output.dataset_names=%s\" % self._dataset_names)\n if self._partiality_threshold:\n self.add_command_line(\n \"partiality_threshold=%s\" % self._partiality_threshold\n )\n self.add_command_line(\"output.html=%s\" % self._html_report)\n\n self.start()\n self.close_wait()\n\n # check for errors\n\n try:\n self.check_for_errors()\n except Exception:\n logger.warning(\n \"dials.merge failed, see log file for more details:\\n %s\",\n self.get_log_file(),\n )\n raise\n\n logger.debug(\"dials.merge status: OK\")\n\n return DialsMergeWrapper()\n","repo_name":"xia2/xia2","sub_path":"src/xia2/Wrappers/Dials/Merge.py","file_name":"Merge.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"85"} +{"seq_id":"40346521358","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as pltick\nimport time\nimport random\nimport sys\nimport sympy\n\ndef time_delay(text, delay_max):\n print()\n for c in text:\n sys.stdout.write(c)\n sys.stdout.flush()\n resttime = random.uniform(0.001, delay_max)\n time.sleep(resttime)\n\ndef quantity_get_print(quant):\n time_delay((\"Value for {0}:..\").format(quant), 0.005)\n try:\n quant_val = float(input())\n return quant_val\n except:\n time_delay(\"You probably have a value error in there somewhere. I need a float!\")\n quit()\n \ndef value_getter():\n time_delay((\"Please provide values for initial velocity magnitude, angular deviation from the positive x axis, normalised drag coefficient, and desired step interval.\"),0.005)\n v_m = quantity_get_print(\"Velocity Magnitude\")\n a_m = quantity_get_print(\"Angular Deviation from Horizontal +X\")\n n_d_c = quantity_get_print(\"Normalised Drag Coefficient\")\n s_i = quantity_get_print(\"Step Interval\")\n return v_m, a_m, n_d_c, s_i\n\n# So we have to generate an iterative method.\n############################################################################\n\"\"\"\nWe have a = -bv^2 * unit_v \nax = -bv^2 cos(theta) \nay = -bv^2 sin(theta) - g\nvx0 = v cos theta0 vy0 = v sin theta0\n\nso\nx0 = 0 y0 = 0\nx1 = x0 + vx0(dt) y1 = y0 + vy0(dt) vx1 = vx0 + ax(dt) vy1 = vy0 + ay(dt)\nxi = x(i-1) + vx(i-1)(dt), etc\nand the theta(i) equals arctan{vy(i)/vx(i)}\n\"\"\"\n############################################################################\n\ndef iterator(v0, a0, B, step):\n x_time, x_velocity, y_time, y_velocity, time, theta = [],[],[],[],[],[]\n x_time.append(0)\n theta.append(a0)\n y_time.append(0)\n x_velocity.append(v0*np.cos(a0))\n y_velocity.append(v0*np.sin(a0))\n time.append(0)\n time_token = 0\n gravity = float(9.81) # Configurable if you'd like. Opted not to.\n \n while True:\n vel_mag = np.sqrt(x_velocity[time_token]**2 + y_velocity[time_token]**2)\n x_accel = lambda L,v,angle: float(-1)*L*(v**2)*np.cos(angle)\n y_accel = lambda L,v,angle,grav: float(-1)*(L*(v**2)*np.sin(angle) + grav)\n new_vx = x_velocity[time_token] + (x_accel(B, vel_mag, theta[time_token]))*step\n new_vy = y_velocity[time_token] + (y_accel(B, vel_mag, theta[time_token], gravity))*step\n new_x = x_time[time_token] + x_velocity[time_token]*step\n new_y = y_time[time_token] + y_velocity[time_token]*step\n new_theta = np.arctan(new_vy/new_vx)\n theta.append(new_theta)\n time.append(step)\n x_time.append(new_x)\n y_time.append(new_y)\n x_velocity.append(new_vx)\n y_velocity.append(new_vy)\n time_token = time_token + int(1)\n if new_y == 0:\n break\n\n return x_time, x_velocity, y_time, y_velocity, time\n\n\nnew_example = iterator(4, np.pi/6, 4, 0.1)\nprint(new_example)\n","repo_name":"callous4567/UoE-Projects","sub_path":"2nd Year Miscellanies - Continued/Moar/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"74330351637","text":"# Rename layers in a pretrained model\n\ncnn = models.vgg19(pretrained=True).features.to(device).eval()\n\nclass Normalization(nn.Module):\n def __init__(self, mean, std):\n super(Normalization, self).__init__()\n # .view the mean and std to make them [C x 1 x 1] so that they can\n # directly work with image Tensor of shape [B x C x H x W].\n # B is batch size. C is number of channels. H is height and W is width.\n self.mean = torch.tensor(mean).view(-1, 1, 1)\n self.std = torch.tensor(std).view(-1, 1, 1)\n\n def forward(self, img):\n # normalize img\n return (img - self.mean) / self.std\n\nmodel = nn.Sequential(normalization)\ni = 0 # increment every time we see a conv\nfor layer in cnn.children():\n if isinstance(layer, nn.Conv2d):\n i += 1\n name = 'conv_{}'.format(i)\n elif isinstance(layer, nn.ReLU):\n name = 'relu_{}'.format(i)\n # The in-place version doesn't play very nicely with the ContentLoss\n # and StyleLoss we insert below. So we replace with out-of-place\n # ones here.\n layer = nn.ReLU(inplace=False)\n elif isinstance(layer, nn.MaxPool2d):\n name = 'pool_{}'.format(i)\n elif isinstance(layer, nn.BatchNorm2d):\n name = 'bn_{}'.format(i)\n else:\n raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))\n\n model.add_module(name, layer)\n","repo_name":"CoffeeCatt/Pytorch-Code-Snippet","sub_path":"Utils/RenameLayer.py","file_name":"RenameLayer.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18138873964","text":"import numpy as np \nimport torchvision.transforms as transforms\nimport torchvision.models as models\nimport torch\nimport torch.nn as nn\nimport time\nimport matplotlib.pyplot as plt\n\nfrom torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nfrom torchvision.datasets import ImageFolder\nfrom torch import optim\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nclass CovidDataset(Dataset):\n def __init__(self, filenames, labels, transform):\n self.filenames = filenames # all file\n self.labels = labels # image tag\n self.transform = transform # transform method\n\n def __len__(self):\n return len(self.filenames)\n\n def __getitem__(self, idx): # idx: Inedx of filenames\n image = Image.open(self.filenames[idx]).convert('RGB')\n image = self.transform(image) # Transform image\n label = np.array(self.labels[idx])\n return image, label\n\n\n# Transformer\ntrain_transformer = transforms.Compose([\n transforms.Resize([299, 299]),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], \n std=[0.229, 0.224, 0.225]),\n])\n\ntest_transformer = transforms.Compose([\n transforms.Resize([299, 299]),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n])\n\n\ndef split_Train_Val_Data(data_path):\n dataset_train = ImageFolder(data_path + '/train')\n dataset_test = ImageFolder(data_path + '/test')\n\n train_inputs, test_inputs = [], []\n train_labels, test_labels = [], []\n\n for x, label in dataset_train.samples:\n train_inputs.append(x)\n train_labels.append(label)\n\n for x, label in dataset_test.samples:\n test_inputs.append(x)\n test_labels.append(label)\n\n # print(len(train_inputs), len(test_inputs))\n\n train_dataloader = DataLoader(CovidDataset(train_inputs, train_labels, train_transformer),\n batch_size=batch_size, shuffle=True)\n test_dataloader = DataLoader(CovidDataset(test_inputs, test_labels, test_transformer),\n batch_size=batch_size, shuffle=False)\n \n return train_dataloader, test_dataloader\n \n\nbatch_size = 32\nlearning_rate = 1e-3\nepochs = 10\ndataset = './CT'\n\ntrain_dataloader, test_dataloader = split_Train_Val_Data(dataset)\nC = models.inception_v3(pretrained=True).to(device)\noptimizer_C = optim.SGD(C.parameters(), lr=learning_rate)\ncriterion = nn.CrossEntropyLoss()\n\nloss_epoch_C = []\ntrain_accuracy, test_accuracy = [], []\nbest_accuracy, best_auc = 0.0, 0.0\n\n# main\nif __name__ == '__main__':\n best = C\n best_acc = 0.0\n for epoch in range(epochs):\n # count time\n start_time = time.time()\n iteration = 0\n correct_train, total_train = 0, 0\n correct_test, total_test = 0, 0\n train_loss_C = 0.0\n \n C.train()\n print('epoch: ' + str(epoch + 1) + ' / ' + str(epochs))\n\n # Training Stage\n for i, (x, label) in enumerate(train_dataloader):\n\n x, label = x.to(device), label.to(device)\n optimizer_C.zero_grad()\n train_output = C(x)\n label = label.long()\n train_output = train_output.logits\n\n train_loss = criterion(train_output, label)\n train_loss.backward()\n optimizer_C.step()\n\n # 計算訓練資料的準確度 (correct_train / total_train)\n _, predicted = torch.max(train_output.data, 1) # 取出預測的 maximum\n total_train += label.size(0)\n correct_train += (predicted == label).sum()\n train_loss_C += train_loss.item()\n iteration += 1\n\n if best_acc < correct_train / total_train:\n best = C\n best_acc = correct_train / total_train\n\n print('Training epoch: %d / loss_C: %.3f | acc: %.3f' % \\\n (epoch + 1, train_loss_C / iteration, correct_train / total_train))\n\n # --------------------------\n # Testing Stage\n # --------------------------\n\n train_accuracy.append(100 * (correct_train / total_train).cpu()) # training accuracy\n # test_accuracy.append(100 * (correct_test / total_test).cpu()) # testing accuracy\n loss_epoch_C.append((train_loss_C / iteration)) # loss\n\n end_time = time.time()\n print('Cost %.3f(secs)' % (end_time - start_time))\n\n C = best\n C.eval()\n\n all_negatives, all_positives = 0, 0\n true_negatives, false_negatives = 0, 0\n true_positives, false_positives = 0, 0\n for i, (x, label) in enumerate(test_dataloader):\n with torch.no_grad():\n x, label = x.to(device), label.to(device)\n label = label.long()\n test_output = C(x)\n test_loss = criterion(test_output, label)\n\n _, predicted = torch.max(test_output.data, 1)\n total_test += label.size(0)\n correct_test += (predicted == label).sum()\n\n pred = np.array(predicted.cpu())\n lbl = np.array(label.cpu())\n # print(pred)\n # print(lbl)\n for idx in range(len(pred)):\n if pred[idx]==0:\n if lbl[idx]==0: true_negatives += 1\n else: false_negatives += 1\n else:\n if lbl[idx]==1: true_positives += 1\n else: false_positives += 1\n\n # print('fp',false_positives)\n # print('tp',true_positives)\n precision = true_positives/(true_positives+false_positives)\n recall = true_positives/(true_positives+false_negatives)\n\n print('Testing F1 score: ', (2*precision*recall)/(precision+recall))\n print('Testing acc: %.3f' % (correct_test / total_test))\n\n torch.save(C, 'model.pt')\n\nplt.figure()\nplt.plot(list(range(epochs)), loss_epoch_C) # plot your loss\nplt.title('Training Loss')\nplt.ylabel('loss'), plt.xlabel('epoch')\nplt.legend(['loss_C'], loc = 'upper left')\nplt.savefig('loss.png')\nplt.show()\n\nplt.figure()\nplt.plot(list(range(epochs)), train_accuracy) # plot your training accuracy\nplt.title('Training acc')\nplt.ylabel('acc (%)'), plt.xlabel('epoch')\nplt.legend(['training acc'], loc = 'upper left')\nplt.savefig('acc.png')\nplt.show()\n","repo_name":"Alanhsu1/Intro_AI","sub_path":"InceptionV3.py","file_name":"InceptionV3.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23186562050","text":"import requests\nimport re\nfrom bs4 import BeautifulSoup\nfrom geopy.geocoders import Nominatim\n\ngeolocator = Nominatim(user_agent=\"get_city_name\")\n\nurl = \"https://uk-air.defra.gov.uk/latest/currentlevels?view=site\"\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'}\n\nresult = requests.get(url,headers=headers)\nsoup = BeautifulSoup(result.text,'lxml')\n\nlinks = []\nfor link in soup.find_all('a', attrs={'href': re.compile(\"../networks/site-info\")}):\n links.append(link.get('href'))\n\nfull_links = []\nfor link in links:\n full_link = link.replace('..', 'http://uk-air.defra.gov.uk')\n full_links.append(full_link)\n\nfor full_link in full_links:\n site_id = full_link.replace('http://uk-air.defra.gov.uk/networks/site-info?site_id=', '')\n result2 = requests.get(full_link,headers=headers)\n soup2 = BeautifulSoup(result2.text,'lxml')\n\n uk_air_id = soup2.find(text=re.compile(\"UK-AIR ID:\")).find_parent(\"p\").get_text().replace(\"UK-AIR ID: \",\"\")\n eu_site_id = soup2.find(text=re.compile(\"EU Site ID:\")).find_parent(\"p\").get_text().replace(\"EU Site ID: \",\"\")\n region = soup2.find(text=re.compile(\"Government Region:\")).find_parent(\"p\").get_text().replace(\"Government Region: \",\"\")\n coordinates = soup2.find(text=re.compile(\"Latitude/Longitude:\")).find_parent(\"p\").get_text().replace(\"Latitude/Longitude: \",\"\")\n latitude,longitude = coordinates.split(', ')\n\n h1 = soup2.find_all(string=re.compile(\"Site Information for\"))[0]\n name = h1.split(\"(\")[0].replace(' Site Information for ', '')\n\n worldlocation = geolocator.reverse(coordinates, exactly_one=True)\n address = worldlocation.raw['address']\n city = address.get('city', '')\n\n print(uk_air_id + ',' + eu_site_id + ',' + site_id + ',' + name + ',' + city + ',' + region + ',' + latitude + ',' + longitude)","repo_name":"iuruoy-shao/Webscraping-UK-air","sub_path":"WebscrapingUK.py","file_name":"WebscrapingUK.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"3402010250","text":"#Ryne Bigueras\r\n#2/26/22\r\n\r\n#Problem 4:Search on the internet for a way to calculate an approximation for pi.\r\n#There are many that use simple arithmetic.\r\n#Write a program to compute the approximation and then print that value as well\r\n#as the value of math.pi from the math module.\r\n\r\ndef pi():\r\n pi = 0\r\n b = 4\r\n c = 1\r\n for i in range(1, 1000000):\r\n a = 2 * ( i % 2 ) - 1\r\n pi += a * b / c\r\n c += 2\r\n print(pi)\r\n\r\npi()\r\n\r\n\r\nimport math\r\n\r\nprint (math.pi)\r\n","repo_name":"MasterPnut/Mod6-CSS225","sub_path":"Problem 4 pi.py","file_name":"Problem 4 pi.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41695287283","text":"import time\n\nfrom core import core\n\n\nstart_time = time.time()\noutput_path = core.process_file(True, \"resources/input.avi\", \"mp4\")\nend_time = time.time()\nelapsed = end_time - start_time\nprint(\"file generated in {:4.3f}s, path: {}\".format(elapsed, output_path))\n","repo_name":"SupinfoProjects/transcode","sub_path":"tests/test-video.py","file_name":"test-video.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15254620921","text":"import os\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom Yahoo import YahooStats\nimport re\nimport datetime\nimport keyboard\nimport time\n\n\nCOMPANIES_LIST_LOCATION = r\"..\\..\\database\\companies\\asx.csv\"\nSTATISTICS_LOCATION = r\"..\\..\\database\\daily\\asx.csv\"\n\nSTATS_DATABASE_LOC = r\"..\\..\\database\\historical\\asx\\stats\\{0}.csv\"\nLAST_UPDATED = r\"..\\..\\database\\historical\\asx\\stats\\last_updated\\{0}.txt\"\n\n\ndef get_statistics(date):\n yahoo = YahooStats()\n columns = ['asx code', 'Date', 'sector'] + yahoo.ROW_TITLES\n pause = False\n companies = pd.read_csv(COMPANIES_LIST_LOCATION)\n n_rows = companies.shape[0]\n \n statistics_df = pd.DataFrame(columns=columns)\n print(\"Hold 'p' to pause and 'r' to resume\")\n for i,company in companies.iterrows():\n while(True):\n if pause or keyboard.is_pressed('p'):\n pause = True\n if not pause or keyboard.is_pressed('r'):\n pause = False\n break\n time.sleep(2)\n \n print(\"Scraping stock \" + str(i+1) + \"/\" + str(n_rows), end=\"\\r\")\n \n yahoo.set_stock(company['ASX code'])\n statistics_df = statistics_df.append(pd.DataFrame([[yahoo.stock,date,company['GICS industry group']] + yahoo.get_stats()],columns=columns),ignore_index=True)\n\n if os.path.isfile(STATISTICS_LOCATION):\n os.remove(STATISTICS_LOCATION)\n\n statistics_df.drop_duplicates().to_csv(STATISTICS_LOCATION,index=False)\n\n\ndef append_stats(date):\n df = pd.read_csv(STATISTICS_LOCATION)\n columns = df.columns\n n_companies = df.shape[0]\n # there's no check for the last time this was updated. Instead it's possible to use drop_duplicates() as shown in https:\\\\jamesrledoux.com\\code\\drop_duplicates\n # to avoid dealing with them later on\n for i,company in df.iterrows():\n print(str(i+1) + \"/\" + str(n_companies),end=\"\\r\")\n if os.path.isfile(STATS_DATABASE_LOC.format(company['asx code'])):\n temp = pd.read_csv(STATS_DATABASE_LOC.format(company['asx code']))\n temp = temp.append(company,ignore_index=True)\n temp.to_csv(STATS_DATABASE_LOC.format(company['asx code']),index=False)\n else:\n try:\n temp = pd.DataFrame([company.values],columns=columns)\n temp.to_csv(STATS_DATABASE_LOC.format(company['asx code']),index=False)\n break\n except:\n print(\"Error, couldn't create file: \" + STATS_DATABASE_LOC.format(company['asx code']))\n print(\"Check that directory exists and that the file name isn't an invalid one for windows\")\n print(\"The company will be ignored\")\n continue\n\n #currently only doing this in case I want to use it in the future for something \n with open(LAST_UPDATED.format(company['asx code']),\"w\") as f:\n f.write(date)\n\n\nif __name__ == \"__main__\":\n #get_statistics(datetime.date.today().strftime(\"%Y-%m-%d\"))\n append_stats(datetime.date.today().strftime(\"%Y-%m-%d\"))","repo_name":"JPDaly/Trading","sub_path":"code/scraping/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"43410958597","text":"#Author: Kai Huang\n#Date: 2015.04.20\n\n#Author: Kai Huang\n#Date: 2015.04.01\n\nimport sys\nsys.path.append(\"../tools\")\nimport DateConversion\nimport StringProcessing\n\n#read\nlines = open(\"../../../data/enron/out.enron\", \"r\")\nnodes = {}\nfor line in lines:\n\ttokens = StringProcessing.SplitLine(line)\n\tif tokens[0] != tokens[1]:\n\t\tif int(tokens[0]) not in nodes:\n\t\t\tnodes[int(tokens[0])] = []\n\t\tnewLine = \"\".join([tokens[0], ' ', tokens[1], ' ', tokens[2], ' ', tokens[3], ' ', DateConversion.SecsToYear(int(tokens[3])), '\\n'])\n\t\tnodes[int(tokens[0])].append(newLine)\n\t\t\n\t\tif int(tokens[1]) not in nodes:\n\t\t\tnodes[int(tokens[1])] = []\n\t\tnewLine = \"\".join([tokens[1], ' ', tokens[0], ' ', tokens[2], ' ', tokens[3], ' ', DateConversion.SecsToYear(int(tokens[3])), '\\n'])\n\t\tnodes[int(tokens[1])].append(newLine)\nlines.close()\n#write\nsortedLines = open(\"../../../data/enron/sorted_out.enron\", \"w\")\nfor i in nodes:\n\tfor j in nodes[i]:\n\t\tsortedLines.write(j)\nsortedLines.close()","repo_name":"khuanghonka/LinkPrediction","sub_path":"bachelor's degree thesis/code/directed/processing/SortNodes.py","file_name":"SortNodes.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39464166479","text":"import os, sys\nimport res.ico_debug\nimport Ui_aml_debug\n\nfrom PyQt5.QtGui import QIcon, QTextCursor\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox\n\nfrom src.common.aml_ini_parser import amlParserIniContainer\nfrom res.script.constant import AmlDebugConstant\nfrom src.common.aml_common_utils import AmlCommonUtils\nfrom src.common.aml_debug_base_ui import AmlDebugModule\n\nclass AmlDebugUi(Ui_aml_debug.Ui_MainWindow, QMainWindow):\n terminalLogSignal = pyqtSignal(str, str)\n def __init__(self):\n super(AmlDebugUi, self).__init__()\n super().setupUi(self)\n AmlDebugModule.initModule(self)\n \n import src.common.aml_common_ui\n self.m_commonUi = src.common.aml_common_ui.instance(self)\n self.m_commonUi.signals_connect_slots()\n self.terminalLogSignal.connect(self.terminalLog)\n AmlCommonUtils.set_log_fuc(self.terminalLogSignal.emit)\n\n def terminalLog(self, log, level=AmlCommonUtils.AML_DEBUG_LOG_LEVEL_D):\n log = AmlCommonUtils.get_current_time() + ' ' + level + ' ' + log\n self.AmlDebugTerminalLog_textBrowser.append(log)\n self.AmlDebugTerminalLog_textBrowser.moveCursor(QTextCursor.End)\n\n def closeEvent(self, event):\n reply = QMessageBox.question(self, 'Amlogic Tips',\"Confirm exit?\", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n event.accept()\n AmlDebugModule.closeEvent() \n else:\n event.ignore()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ret = AmlCommonUtils.init()\n if ret != 0:\n exit\n amlParserIniContainer.initParser()\n ui = AmlDebugUi()\n \n ui.setWindowIcon(QIcon(AmlCommonUtils.AML_DEBUG_TOOL_ICO_PATH))\n ui.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint) \n ui.setFixedSize(ui.width(), ui.height())\n ui.setWindowTitle(\"Amlogic Debug Tool v\" + AmlDebugConstant.AML_DEBUG_TOOL_ABOUT_VERSION)\n ui.show()\n ret, version = AmlCommonUtils.check_for_updates()\n if ret == 1:\n reply = QMessageBox.question(ui, 'Online updater', 'There is new version: ' + version + '.\\n Update now? ', \n QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n if reply == QMessageBox.Yes:\n AmlCommonUtils.update_tool_now()\n sys.exit(app.exec_())\n","repo_name":"zgyhc2050/amlogic_debug_tool","sub_path":"aml_debug_tool.py","file_name":"aml_debug_tool.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"7413529235","text":"from sqlalchemy.orm import relationship, Mapped\nfrom sqlalchemy import Column, Integer, Enum, Float, String, Boolean, ForeignKey\nimport configparser\nimport enum\nfrom typing import Optional, Dict, TYPE_CHECKING\n\nfrom joule.models.meta import Base\nfrom joule.errors import ConfigurationError\n\nif TYPE_CHECKING: # pragma: no cover\n from joule.models.folder import DataStream\n\n\nclass Element(Base):\n \"\"\"\n Attributes:\n name (str): element name\n index (int): order of element in the stream\n units (str): data unit (eg Watts, Volts, etc)\n plottable (bool): whether the data can be visualized as a time series\n offset (float): linear scaling y=mx+b, only applied to Lumen visualizations\n scale_factor (float): linear scaling only applied to Lumen visualizations\n default_min (float): fix lower limit on autoscaling in Lumen visualizations\n default_max (float): fix upper limit on autoscaling in Lumen visualizations\n display_type (Element.DISPLAYTYPE): visualization type\n \"\"\"\n __tablename__ = 'element'\n __table_args__ = {\"schema\": \"metadata\"}\n\n id: int = Column(Integer, primary_key=True)\n index: int = Column(Integer, nullable=False)\n name: str = Column(String)\n units: str = Column(String)\n plottable: bool = Column(Boolean)\n\n class DISPLAYTYPE(enum.Enum):\n DISCRETE = enum.auto()\n CONTINUOUS = enum.auto()\n EVENT = enum.auto()\n\n display_type: DISPLAYTYPE = Column(Enum(DISPLAYTYPE),\n default=DISPLAYTYPE.CONTINUOUS)\n\n offset: float = Column(Float, default=0, nullable=False)\n scale_factor: float = Column(Float, default=1.0, nullable=False)\n default_max: Optional[float] = Column(Float, default=None)\n default_min: Optional[float] = Column(Float, default=None)\n stream_id: int = Column(Integer, ForeignKey('metadata.stream.id'))\n stream: Mapped['DataStream'] = relationship(\"DataStream\", back_populates=\"elements\")\n\n def __repr__(self):\n return \"\" % (self.name, self.units, self.display_type)\n\n def __eq__(self, other):\n if not isinstance(other, Element):\n return False\n return (self.name == other.name and\n self.index == other.index and\n self.units == other.units and\n self.plottable == other.plottable and\n self.display_type == other.display_type and\n self.offset == other.offset and\n self.scale_factor == other.scale_factor and\n self.default_max == other.default_max and\n self.default_min == other.default_min)\n\n def to_json(self):\n \"\"\"\n\n Returns: Dictionary of Element attributes\n\n \"\"\"\n if self.display_type is None:\n # make up a default value\n self.display_type = Element.DISPLAYTYPE.CONTINUOUS\n return {\n 'id': self.id,\n 'index': self.index,\n 'name': self.name,\n 'units': self.units,\n 'plottable': self.plottable,\n 'display_type': self.display_type.name,\n 'offset': self.offset,\n 'scale_factor': self.scale_factor,\n 'default_max': self.default_max,\n 'default_min': self.default_min\n }\n\n def to_nilmdb_metadata(self):\n return {\n 'column': self.index,\n 'name': self.name,\n 'units': self.units,\n 'scale_factor': self.scale_factor,\n 'offset': self.offset,\n 'plottable': True, # TODO: check why elements have NULL fields here?\n 'discrete': False,\n 'default_min': self.default_min,\n 'default_max': self.default_max\n }\n\n def update_attributes(self, attrs: Dict):\n if 'name' in attrs:\n self.name = validate_name(attrs['name'])\n if 'units' in attrs:\n self.units = attrs['units']\n try:\n if 'plottable' in attrs:\n self.plottable = bool(attrs['plottable'])\n if 'offset' in attrs:\n self.offset = float(attrs['offset'])\n if 'scale_factor' in attrs:\n self.scale_factor = float(attrs['scale_factor'])\n if 'display_type' in attrs:\n self.display_type = validate_type(attrs['display_type'])\n if 'default_max' in attrs:\n x = attrs['default_max']\n if x is not None:\n x = float(x)\n self.default_max = x\n if 'default_min' in attrs:\n x = attrs['default_min']\n if x is not None:\n x = float(x)\n self.default_min = x\n except ValueError as e:\n raise ConfigurationError(\"Invalid element configuration: %r\" % e)\n if self.default_max is not None and self.default_min is not None:\n if self.default_max <= self.default_min:\n raise ConfigurationError(\"[default_min] must be > [default_max]\")\n\n\ndef from_json(data: Dict) -> Element:\n return Element(id=data[\"id\"],\n index=data[\"index\"],\n name=validate_name(data[\"name\"]),\n units=data[\"units\"],\n plottable=data[\"plottable\"],\n display_type=validate_type(data[\"display_type\"].upper()),\n offset=data[\"offset\"],\n scale_factor=data[\"scale_factor\"],\n default_max=data[\"default_max\"],\n default_min=data[\"default_min\"])\n\n\ndef from_config(config: configparser.ConfigParser) -> Element:\n name = validate_name(config[\"name\"])\n display_type = validate_type(config.get(\"display_type\", fallback=\"continuous\"))\n units = config.get(\"units\", fallback=None)\n plottable = _get_bool(\"plottable\", config, True)\n offset = _get_float(\"offset\", config, 0.0)\n scale_factor = _get_float(\"scale_factor\", config, 1.0)\n default_max = _get_float(\"default_max\", config, None)\n default_min = _get_float(\"default_min\", config, None)\n # make sure min<=max if set\n if ((default_max is not None and default_min is not None) and\n (default_min >= default_max)):\n raise ConfigurationError(\"set default_min Element:\n # cannot assume any structure to the config dict\n default_config = {\n \"name\": \"elem%d\" % default_index,\n \"units\": None,\n \"plottable\": True,\n \"offset\": 0,\n \"scale_factor\": 1.0,\n \"default_max\": None,\n \"default_min\": None,\n \"index\": default_index,\n \"discrete\": False\n }\n merged_config = {**default_config, **config}\n display_type = Element.DISPLAYTYPE.CONTINUOUS\n if merged_config['discrete']:\n display_type = Element.DISPLAYTYPE.EVENT\n\n return Element(name=merged_config[\"name\"],\n display_type=display_type,\n units=merged_config['units'],\n plottable=merged_config['plottable'],\n offset=merged_config['offset'],\n scale_factor=merged_config['scale_factor'],\n default_max=merged_config['default_max'],\n default_min=merged_config['default_min'],\n index=merged_config['column'])\n\n\ndef validate_name(name: str) -> str:\n if name == \"\":\n raise ConfigurationError(\"missing name\")\n return name\n\n\ndef validate_type(display_type: str) -> Element.DISPLAYTYPE:\n try:\n return Element.DISPLAYTYPE[display_type.upper()]\n except KeyError as e:\n valid_types = \", \".join([m.name.lower() for m in Element.DISPLAYTYPE])\n raise ConfigurationError(\"invalid display_type [%s], choose from [%s]\" %\n (display_type, valid_types)) from e\n\n\ndef _get_bool(setting: str, config: configparser.ConfigParser, default: bool):\n try:\n return config.getboolean(setting, default)\n except ValueError as e:\n raise ConfigurationError(\"[%s] invalid value, use True/False\" % setting) from e\n\n\ndef _get_float(setting: str, config: configparser.ConfigParser, default):\n try:\n if config[setting] == \"None\":\n return default\n return config.getfloat(setting, default)\n except KeyError:\n return default\n except ValueError as e:\n raise ConfigurationError(\"[%s] invalid value, must be a number\" %\n setting) from e\n","repo_name":"wattsworth/joule","sub_path":"joule/models/element.py","file_name":"element.py","file_ext":"py","file_size_in_byte":8857,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"26008455444","text":"import re\nfrom app.controllers import config as conf\n\n\ntext = \"i spent 1 day and 2.5 hours on the issue ttj-12 and then found out the issue was removed.\" \\\n + \"please update me with comment as i have no comment.\"\n\n\ndef test_number_pattern():\n expected = ['1', '2.5', '12']\n matches = re.finditer(conf.COMMON_PATTERN_NUMBER, text)\n numbers = [m.group() for m in matches]\n\n assert expected == numbers\n\n\ndef test_time_pattern():\n expected = ['day', 'hours']\n matches = re.finditer(conf.COMMON_PATTERN_TIMEUNIT, text)\n timeunits = [m.group() for m in matches]\n\n assert expected == timeunits\n\n\ndef test_timespent_pattern():\n expected = ['1 day', '2.5 hours']\n matches = re.finditer(conf.COMMON_PATTERN_TIMESPENT, text)\n timespents = [m.group() for m in matches]\n\n assert expected == timespents\n\n\ndef test_issuekey_pattern():\n expected = ['ttj-12']\n matches = re.finditer(conf.COMMON_PATTERN_ISSUEKEY, text)\n issue_keys = [m.group() for m in matches]\n\n assert expected == issue_keys\n\n\ndef test_comment_pattern():\n expected = ['i have no comment.']\n matches = re.finditer(conf.COMMON_PATTERN_COMMENT, text)\n comments = [m.group() for m in matches]\n\n assert expected == comments\n","repo_name":"William-Li-Wei/talk-to-jira","sub_path":"tests/app/controllers/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34032607081","text":"#!/bin/python\n# -*- coding: utf8 -*-\nimport sys\nimport os\nimport re\n\n#请完成下面这个函数,实现题目要求的功能\n#当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^ \n#******************************开始写代码******************************\ndef upper_bound(nums, target):\n if(len(nums)==0):\n return 0\n low, high = 0, len(nums)-1\n pos = len(nums)\n while low\n high = mid\n pos = high\n if nums[low]>target:\n pos = low\n return pos\n\n\ndef calcMinStaff():\n n=int(input())\n nums=[]\n for _ in range(n):\n nums.append([int(i) for i in input().split(',') ])\n nums.sort(key= lambda x:x[0])\n\n res=[]\n for x,y in nums:\n \n \n pos=upper_bound(res,x)-1\n \n if pos!=-1:\n res.pop(pos)\n \n ins=upper_bound(res,y)\n res.insert(ins,y)\n \n \n return len(res)\n\n#******************************结束写代码******************************\n\n\n \nres = calcMinStaff()\n\nprint(str(res) + \"\\n\")\n\n\n","repo_name":"gentlegant/leetcode","sub_path":"xiecheng2.py","file_name":"xiecheng2.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"13094451462","text":"#Christian Hill\r\n#Prgram 06\r\n#COMS-170-OE01\r\n# This program will read all of the numbers stored in a file,\r\n#calculate the total and display the value as total points, calculate the average score\r\n#then display the value as a percent score, and will handle IOError/ValueError exceptions.\r\n# ----------------------------------------------------------------------------\r\n# Variable Type Purpose\r\n# ----------------------------------------------------------------------------\r\n# fltTotal Integer Calculates the total sum of the numbers found on the data file\r\n# amount Float Calculates the total average percent of the numbers found on the datat file\r\n# count Integer Wil read the rest of the file until there is no more data\r\n \r\ndef main():\r\n print(\"--------------------------------------------------------\")\r\n print(\"This program will take the total and the percent average from a data file\")\r\n print(\"--------------------------------------------------------\")\r\n\r\n try:\r\n #Start total accumlator at 0\r\n fltTotal = 0\r\n count = 0\r\n \r\n #open the file for reading\r\n infile = open('numdata.txt.','r')\r\n \r\n #read the first line of the file\r\n line = infile.readline()\r\n\r\n #read until no more data\r\n while line != \"\":\r\n #convert string value to number\r\n fltValue = float(line)\r\n \r\n #add to the total\r\n fltTotal += float(fltValue)\r\n line = infile.readline()\r\n\r\n #add to the count\r\n count += 1\r\n \r\n #close the file\r\n infile.close()\r\n\r\n #Display the numbers and print their total\r\n print('The Numbers are: ', count)\r\n print('Their total is: ', fltTotal)\r\n\r\n #calculate the percent average amount\r\n amount = fltTotal/count\r\n \r\n #Display the numbers and print their percent amount\r\n print ('Their average is: ', format (amount, '9,.2f'), '%')\r\n\r\n except IOError:\r\n #program encountered a read error\r\n print('An error(1) occures while reading a data file')\r\n\r\n except ValueError:\r\n # program encountered a numeric value error\r\n print('An error(2) occures while reading a data file')\r\n else:\r\n #if no errors were encountered\r\n print(\"--------------------------------------------------------\")\r\n print(\"No errors discovered\")\r\n finally:\r\n # this occurs whether there are errors or not\r\n print(\"--------------------------------------------------------\")\r\n\r\n \r\n#Call the main function\r\nmain()\r\n \r\n\r\n","repo_name":"chrihill/COM170-Python-Programming","sub_path":"06 Files and Exceptions Final program.py","file_name":"06 Files and Exceptions Final program.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16327446791","text":"# -*- coding: utf-8 -*-\n#------------------------------------------------------------\nimport sys\nPY3 = False\nif sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int\n\nif PY3:\n import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo\nelse:\n import urlparse # Usamos el nativo de PY2 que es más rápido\n\nimport re\n\nfrom platformcode import config, logger\nfrom core import scrapertools\nfrom core.item import Item\nfrom core import servertools\nfrom core import httptools\nfrom bs4 import BeautifulSoup\n\ncanonical = {\n 'channel': 'pornmz', \n 'host': config.get_setting(\"current_host\", 'pornmz', default=''), \n 'host_alt': [\"https://pornmz.net/\"], \n 'host_black_list': [], \n 'set_tls': True, 'set_tls_min': True, 'retries_cloudflare': 1, 'cf_assistant': False, \n 'CF': False, 'CF_test': False, 'alfa_s': True\n }\nhost = canonical['host'] or canonical['host_alt'][0]\n\n ############################# cloudflare ###################################\ndef mainlist(item):\n logger.info()\n itemlist = []\n itemlist.append(item.clone(title=\"Nuevos\" , action=\"lista\", url=host + \"?filter=latest\"))\n itemlist.append(item.clone(title=\"Mas vistos\" , action=\"lista\", url=host + \"?filter=most-viewed\"))\n itemlist.append(item.clone(title=\"Mejor valorado\" , action=\"lista\", url=host + \"?filter=popular\"))\n itemlist.append(item.clone(title=\"Mas metraje\" , action=\"lista\", url=host + \"?filter=longest\"))\n itemlist.append(item.clone(title=\"PornStar\" , action=\"categorias\", url=host + \"actors\"))\n itemlist.append(item.clone(title=\"Canal\" , action=\"canal\", url=host))\n itemlist.append(item.clone(title=\"Categorias\" , action=\"categorias\", url=host + \"categories\"))\n itemlist.append(item.clone(title=\"Buscar\", action=\"search\"))\n return itemlist\n\n\ndef search(item, texto):\n logger.info()\n texto = texto.replace(\" \", \"+\")\n item.url = \"%s?s=%s\" % (host,texto)\n try:\n return lista(item)\n except:\n import sys\n for line in sys.exc_info():\n logger.error(\"%s\" % line)\n return []\n\n\ndef canal(item):\n logger.info()\n itemlist = []\n soup = create_soup(item.url).find('nav', id='site-navigation')\n matches = soup.find_all('a', href=re.compile(r\"^%spmvideo/(?:s|c)/\\w+\" %host))\n for elem in matches:\n url = elem['href']\n title = elem.text\n thumbnail = \"\"\n plot = \"\"\n itemlist.append(item.clone(action=\"lista\", title=title, url=url,\n fanart=thumbnail, thumbnail=thumbnail , plot=plot) )\n return itemlist\n\n\ndef categorias(item):\n logger.info()\n itemlist = []\n soup = create_soup(item.url) \n matches = soup.find_all('article',id=re.compile(r\"^post-\\d+\"))\n for elem in matches:\n url = elem.a['href']\n title = elem.a['title']\n thumbnail = elem.img\n if thumbnail:\n thumbnail = thumbnail['src']\n plot = \"\"\n itemlist.append(item.clone(action=\"lista\", title=title, url=url,\n fanart=thumbnail, thumbnail=thumbnail , plot=plot) )\n next_page = soup.find('a', class_='current')\n if next_page:\n next_page = next_page.parent.find_next_sibling(\"li\").a['href']\n next_page = urlparse.urljoin(item.url,next_page)\n itemlist.append(item.clone(action=\"categorias\", title=\"[COLOR blue]Página Siguiente >>[/COLOR]\", url=next_page) )\n return itemlist\n\n\ndef create_soup(url, referer=None, unescape=False):\n logger.info()\n if referer:\n data = httptools.downloadpage(url, headers={'Referer': referer}, canonical=canonical).data\n else:\n data = httptools.downloadpage(url, canonical=canonical).data\n if unescape:\n data = scrapertools.unescape(data)\n soup = BeautifulSoup(data, \"html5lib\", from_encoding=\"utf-8\")\n return soup\n\n\ndef lista(item):\n logger.info()\n itemlist = []\n soup = create_soup(item.url)\n matches = soup.find_all('article',id=re.compile(r\"^post-\\d+\"))\n for elem in matches:\n url = elem.a['href']\n title = elem.a['title']\n thumbnail = elem.img\n if thumbnail:\n thumbnail = thumbnail['src']\n else:\n thumbnail = elem.video['poster']\n stime = elem.find('span', class_='duration')\n actors = elem['class']\n actriz = \"\"\n for x in actors:\n if not \"actors-\" in x:\n continue\n actor = x.replace(\"actors-\", \"\").replace(\"-\", \" \")\n actriz += \"%s, \" %actor\n if actriz:\n title = \"(%s) %s\" %(actriz[:-2], title)\n if stime:\n stime = stime.text.strip()\n title = \"[COLOR yellow]%s[/COLOR] %s\" % (stime,title)\n if \"px.gif\" in thumbnail:\n thumbnail = elem.img['data-src']\n plot = \"\"\n action = \"play\"\n if logger.info() == False:\n action = \"findvideos\"\n itemlist.append(Item(channel=item.channel, action=action, title=title, contentTitle=title, url=url,\n fanart=thumbnail, thumbnail=thumbnail , plot=plot) )\n next_page = soup.find('a', class_='current')\n if next_page:\n next_page = next_page.parent.find_next_sibling(\"li\").a['href']\n next_page = urlparse.urljoin(item.url,next_page)\n itemlist.append(item.clone(action=\"lista\", title=\"[COLOR blue]Página Siguiente >>[/COLOR]\", url=next_page) )\n return itemlist\n\n\ndef findvideos(item):\n logger.info()\n itemlist = []\n soup = create_soup(item.url).find('div', class_='responsive-player')\n url = soup.find('iframe')['src']\n url = urlparse.urljoin(item.url,url)\n soup = create_soup(url, referer=item.url)#.find('video', id='video')\n matches = soup.find_all('source')\n for elem in matches:\n url = elem['src']\n if elem.has_attr('title'):\n quality = elem['title']\n else:\n quality = \"mp4\"\n url += \"|Referer=%s\" % item.url\n itemlist.append(item.clone(action=\"play\", title=quality, url=url) )\n if not matches:\n url = soup.find('iframe')['src']\n url = create_soup(url).find('iframe')['src']\n itemlist.append(item.clone(action=\"play\", title= \"%s\", contentTitle = item.title, url=url))\n itemlist = servertools.get_servers_itemlist(itemlist, lambda i: i.title % i.server.capitalize())\n return itemlist[::-1]\n\n\ndef play(item):\n logger.info()\n itemlist = []\n soup = create_soup(item.url).find('div', class_='responsive-player')\n url = soup.find('iframe')['src']\n url = urlparse.urljoin(item.url,url)\n soup = create_soup(url)#.find('video', id='video')\n matches = soup.find_all('source')\n for elem in matches:\n url = elem['src']\n if elem.has_attr('title'):\n quality = elem['title']\n else:\n quality = \"mp4\"\n url += \"|Referer=%s\" % item.url\n itemlist.append(['%s' %quality, url])\n if not matches:\n url = soup.find('iframe')['src']\n url = create_soup(url).find('iframe')['src']\n itemlist.append(item.clone(action=\"play\", title= \"%s\", contentTitle = item.title, url=url))\n itemlist = servertools.get_servers_itemlist(itemlist, lambda i: i.title % i.server.capitalize())\n return itemlist[::-1]\n","repo_name":"alfa-addon/addon","sub_path":"plugin.video.alfa/channels/pornmz.py","file_name":"pornmz.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"85"} +{"seq_id":"15684983433","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nfrom sonnet.python.modules import base\n\n\nclass Sequential(base.AbstractModule):\n \"\"\"Builds a module out of a sequence of callables.\n\n Note that `Sequential` is limited in the range of possible architectures\n it can handle. This is a deliberate design decision; `Sequential` is only\n meant to be used for the simple case of fusing together modules/ops where\n the input of a particular module/op is the output of the previous one. Another\n restriction is that it is not possible to have extra arguments in the `_build`\n method that are passed to the constituents of the module - for example,\n if there is a `BatchNorm` module in `Sequential` and the user wishes to switch\n the `is_training` flag. If this is the desired use case, the recommended\n solution is to use `snt.Module` to wrap a custom function, as shown in the\n following example:\n\n https://github.com/deepmind/sonnet/examples/module_with_build_args.py\n \"\"\"\n\n def __init__(self, layers, name=\"sequential\"):\n \"\"\"Constructs a Sequential module.\n\n This feeds the output of each layer into the next and returns the output\n of the final layer.\n\n If a layer returns a tuple, it is assumed that this must be unpacked into\n the argument list of the next layer. If it is not a tuple, it is simply\n passed through to the next layer unchanged.\n\n Args:\n layers: Iterable of callables to stack together, which can be modules\n or ops.\n name: Name of the module.\n\n Raises:\n TypeError: If `layers` is None or contains any non-callable items.\n \"\"\"\n super(Sequential, self).__init__(name=name)\n\n # Store a copy of the iterable in a tuple to ensure users cannot modify the\n # iterable later, and protect against iterables which can only be read once.\n self._layers = tuple(layers)\n\n is_not_callable = [(i, mod) for i, mod in enumerate(self._layers)\n if not callable(mod)]\n\n if is_not_callable:\n raise TypeError(\"Items {} not callable with types: {}\".format(\n \", \".join(str(i) for i, _ in is_not_callable),\n \", \".join(type(layer).__name__ for _, layer in is_not_callable)))\n\n def _build(self, *args):\n \"\"\"Connects the Sequential module into the graph.\n\n Args:\n *args: A tuple of inputs, to be unpacked as the arguments to the first\n layer.\n\n Returns:\n The output value of the last layer.\n \"\"\"\n net = args\n\n for layer in self._layers:\n if isinstance(net, tuple):\n net = layer(*net)\n else:\n net = layer(net)\n\n return net\n\n @property\n def layers(self):\n return self._layers\n","repo_name":"AlphaSmartDog/DeepLearningNotes","sub_path":"Note-6 A3CNet/Note-6.4 HS300指数增强/sonnet/python/modules/sequential.py","file_name":"sequential.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":348,"dataset":"github-code","pt":"85"} +{"seq_id":"37149426691","text":"# Your task is to read the input DATAFILE line by line, and for the first 10 lines (not including the header)\n# split each line on \",\" and then for each line, create a dictionary\n# where the key is the header title of the field, and the value is the value of that field in the row.\n# The function parse_file should return a list of dictionaries,\n# each data line in the file being a single list entry.\n# Field names and values should not contain extra whitespace, like spaces or newline characters.\n# You can use the Python string method strip() to remove the extra whitespace.\n# You have to parse only the first 10 data lines in this exercise,\n# so the returned list should have 10 entries!\nimport os\n\nDATADIR = \"\"\nDATAFILE = \"beatles-diskography.csv\"\n\n# This is a version with low efficiency\ndata = []\nwith open(DATAFILE,\"r\") as f:\n for i,line in enumerate(f):\n line_list = line.split(',')\n if i > 0:\n dic = {'Title':line_list[0],'UK Chart Position':line_list[3],'Label':line_list[2],\\\n 'Released':line_list[1],'US Chart Position':line_list[4],\\\n 'RIAA Certification':line_list[6].split('\\n')[0],'BPI Certification':line_list[5]}\n data.append(dic)\n if i > 10:\n break\n\n# Let's improve it a little bit\n### Important\n# Python string method strip() will come in handy to get rid of the extra whitespace \n# (that includes newline character at the end of line)\ndata = []\nwith open(DATAFILE,\"r\") as f:\n head = f.readline().split(',')\n head[-1] = head[-1].split('\\n')[0]\n for i,line in enumerate(f):\n line_list = line.split(',')\n dic = {}\n for j,col in enumerate(head):\n if col == 'RIAA Certification':\n dic[col] = line_list[j].split('\\n')[0]\n else:\n dic[col] = line_list[j].strip()\n data.append(dic)\n if i > 10:\n break\n\n# Add back to the function\ndef parse_file(datafile):\n data = []\n with open(DATAFILE,\"r\") as f:\n head = f.readline().split(',')\n head[-1] = head[-1].split('\\n')[0]\n for i,line in enumerate(f):\n line_list = line.split(',')\n dic = {}\n for j,col in enumerate(head):\n if col == 'RIAA Certification':\n dic[col] = line_list[j].split('\\n')[0]\n else:\n dic[col] = line_list[j].strip()\n data.append(dic)\n if i > 10:\n break\n return data\n\ndef test():\n # a simple test of your implemetation\n datafile = os.path.join(DATADIR, DATAFILE)\n d = parse_file(datafile)\n firstline = {'Title': 'Please Please Me', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '22 March 1963', 'US Chart Position': '-', 'RIAA Certification': 'Platinum', 'BPI Certification': 'Gold'}\n tenthline = {'Title': '', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '10 July 1964', 'US Chart Position': '-', 'RIAA Certification': '', 'BPI Certification': 'Gold'}\n assert d[0] == firstline\n assert d[9] == tenthline\n\ntest()\n\n","repo_name":"nji3/Data_Wrangling_and_MongoDB","sub_path":"parsing CSV files/parseCSV.py","file_name":"parseCSV.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32138736957","text":"import requests\nimport os\nfrom dotenv import load_dotenv\n\n\nload_dotenv()\n\n\ndef send_simple_message(to, subject, body):\n domain = os.getenv(\"MAILGUN_DOMAIN\")\n return requests.post(\n f\"https://api.mailgun.net/v3/{domain}/messages\",\n auth=(\"api\", os.getenv(\"MAILGUN_API_KEY\")),\n data={\n \"from\": f\"Yaseen \",\n \"to\": [to],\n \"subject\": subject,\n \"text\": body,\n },\n )\n\n\ndef send_user_registration_email(email, username):\n return send_simple_message(\n email,\n \"Successfully Signed up!\",\n f\"Hi,{username}! You have Successfully signed up for my REST API!\",\n )\n","repo_name":"yaseeen96/first_project","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28369968776","text":"#!/usr/bin/env python\nimport roslib\nimport rospy\nimport pickle\nimport time\nimport math\nimport string\nimport sys\nimport cv2\nimport geometry_msgs.msg\nimport std_msgs.msg\nimport sensor_msgs.msg\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nfrom sensor_msgs.msg import Image\n\nfrom cv_bridge import CvBridge, CvBridgeError\n\n\ndef addToChart(list, foot, lower, upper):\n data[0].append(foot.quat)\n return\n\n\nDataEntry = namedtuple('DataEntry', \\\n 'quatx quaty quatz quatw \\\n gyrox gyroy gyroz \\\n accelx accely accelz \\\n compx compy compz \\\n label \\\n sequence')\n\nrospy.init_node('annotate')\npref = sys.argv[1]\nimages = []\nbridge = CvBridge()\n\nimages = pickle.load(open(pref + \"_images.p\", \"r\"))\nlower_leg = pickle.load(open(pref + \"_lower_leg.p\", \"rb\"))\nupper_leg = pickle.load(open(pref + \"_upper_leg.p\", \"rb\"))\nfoot = pickle.load(open(pref + \"_foot.p\", \"rb\"))\np_indices = pickle.load(open(pref + \"_indices.p\", \"r\"))\n\nano = cv2.imread(\"ano.png\")\nano = cv2.resize(ano, (640, 480))\ni = 0\nff_ = [[] for i in range(7 * 3)]\nho_ = [[] for i in range(7 * 3)]\nsw_ = [[] for i in range(7 * 3)]\nhs_ = [[] for i in range(7 * 3)]\nif len(sys.argv) == 3:\n if sys.argv[2] == 'c':\n rospy.logwarn(\"Loading Annotations\")\n while foot[i].label != -1:\n i += 1\n elif sys.argv[2] == 'd':\n rospy.logerr(\"Clearing Annotations\")\n for i in range(0, len(foot)):\n foot[i] = foot[i]._replace(label=-1)\n lower_leg[i] = lower_leg[i]._replace(label=-1)\n upper_leg[i] = upper_leg[i]._replace(label=-1)\n i = 0\n\nkeys = [27, 81, 82, 83, 84, 114, 115, 99]\nlabels = [\"FF\", \"HO\", \"SW\", \"HS\"]\ntotal_entries = len(images)\n\nif sys.argv[2] == 'v':\n while (i < total_entries - 10) and (i >= 0):\n print(\"Frame #\" + str(i) + \"/\" + str(total_entries))\n plt_data = []\n plt_data.append(foot[i].quatx)\n plt_data.append(foot[i].quaty)\n plt_data.append(foot[i].quatz)\n plt_data.append(foot[i].quatw)\n plt_data.append(foot[i].gyrox)\n plt_data.append(foot[i].gyroy)\n plt_data.append(foot[i].gyroz)\n\n plt_data.append(lower_leg[i].quatx)\n plt_data.append(lower_leg[i].quaty)\n plt_data.append(lower_leg[i].quatz)\n plt_data.append(lower_leg[i].quatw)\n plt_data.append(lower_leg[i].gyrox)\n plt_data.append(lower_leg[i].gyroy)\n plt_data.append(lower_leg[i].gyroz)\n\n plt_data.append(upper_leg[i].quatx)\n plt_data.append(upper_leg[i].quaty)\n plt_data.append(upper_leg[i].quatz)\n plt_data.append(upper_leg[i].quatw)\n plt_data.append(upper_leg[i].gyrox)\n plt_data.append(upper_leg[i].gyroy)\n plt_data.append(upper_leg[i].gyroz)\n\n k = cv2.waitKey(0)\n k &= 255\n\n plt.figure()\n plt.ylim(ymax=7, ymin=-7)\n plt.title(labels[foot[i].label])\n plt.bar(np.arange(len(plt_data)), plt_data)\n # plt.show(block=False)\n plt.savefig('foo.png')\n foo = cv2.imread(\"foo.png\")\n foo = cv2.resize(foo, (640, 480))\n vis = np.concatenate((images[p_indices[i]], foo), axis=1)\n\n cv2.imshow(\"Annotation Window\", vis)\n k = cv2.waitKey(0)\n k &= 255\n\n if k == 83:\n # RIGHT\n i += 1\n elif k == 81:\n # left\n i -= 1\n elif k == 27:\n cv2.destroyAllWindows()\n exit()\n\n exit()\nwhile i < total_entries:\n print(\"Frame #\" + str(i) + \"/\" + str(total_entries))\n # print images[i].shape\n # vis = np.concatenate((images[i], ano), axis=1)\n vis = np.concatenate((images[p_indices[i]], ano), axis=1)\n\n # cv2.imshow(\"Annotation Window\", images[i])\n cv2.imshow(\"Annotation Window\", vis)\n k = cv2.waitKey(0)\n print (k & 255)\n while k & 255 not in keys:\n print(\"Waiting for correct key\")\n k = cv2.waitKey(0)\n print (k & 255)\n print(\"Key : \" + str(k & 255))\n # k = cv2.waitKey(0)\n k &= 255\n if k == 27:\n cv2.destroyAllWindows()\n exit()\n elif k == 81:\n # LEFT\n # print(\"FF\")\n lower_leg[i] = lower_leg[i]._replace(label=0)\n upper_leg[i] = upper_leg[i]._replace(label=0)\n foot[i] = foot[i]._replace(label=0)\n rospy.logwarn(\"Label : %s\", labels[foot[i].label])\n i += 1\n elif k == 82:\n # UP\n # print(\"HO\")\n lower_leg[i] = lower_leg[i]._replace(label=1)\n upper_leg[i] = upper_leg[i]._replace(label=1)\n foot[i] = foot[i]._replace(label=1)\n rospy.logwarn(\"Label : %s\", labels[foot[i].label])\n i += 1\n elif k == 83:\n # RIGHT\n # print(\"SW\")\n lower_leg[i] = lower_leg[i]._replace(label=2)\n upper_leg[i] = upper_leg[i]._replace(label=2)\n foot[i] = foot[i]._replace(label=2)\n rospy.logwarn(\"Label : %s \", labels[foot[i].label])\n i += 1\n elif k == 84:\n # DOWN\n # print(\"HS\")\n lower_leg[i] = lower_leg[i]._replace(label=3)\n upper_leg[i] = upper_leg[i]._replace(label=3)\n foot[i] = foot[i]._replace(label=3)\n rospy.logwarn(\"Label : %s \", labels[foot[i].label])\n i += 1\n elif k == 114:\n # R\n # GO BACK 10 FRAMES\n rospy.logerr(\"Rewind\")\n i -= 10\n if i < 0:\n i = 0\n elif k == 99:\n # C\n # Skip Frame\n rospy.logwarn(\"Skipped Frame\")\n i += 1\n elif k == 115:\n # pickle.dump(foot, open(pref+\"_foot_annotated.p\",\"wb\"))\n pickle.dump(lower_leg, open(pref + \"_lower_leg.p\", \"wb\"))\n pickle.dump(upper_leg, open(pref + \"_upper_leg.p\", \"wb\"))\n pickle.dump(foot, open(pref + \"_foot.p\", \"wb\"))\n rospy.logerr(\"Saved\")\n # i = i-1\n if i < 0:\n i = 0\n pickle.dump(lower_leg, open(pref + \"_lower_leg_annotated.p\", \"wb\"))\n pickle.dump(upper_leg, open(pref + \"_upper_leg_annotated.p\", \"wb\"))\n pickle.dump(foot, open(pref + \"_foot_annotated.p\", \"wb\"))\n","repo_name":"AssistiveRoboticsUNH/gait_hmm_ros","sub_path":"scripts/annotate.py","file_name":"annotate.py","file_ext":"py","file_size_in_byte":6058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"18724390051","text":"import numpy as np\n\n\ndef metric_fp(y_true, y_pred):\n y_true = y_true.astype(\"uint8\")\n # The try except is needed because when the metric is batched some batches\n # have one class only\n try:\n\n cm = np.array([[np.sum((y_pred < 0.5) & (y_true == 0)), np.sum((y_pred >= 0.5) & (y_true == 0))],\n [np.sum((y_pred < 0.5) & (y_true == 1)), np.sum((y_pred >= 0.5) & (y_true == 1))]])\n\n # Calculate the false positive rate\n fp = cm[0][1] / (cm[0][1] + cm[1][1])\n\n return fp\n\n except ValueError:\n return np.nan\n","repo_name":"musdotdigital/federated-research","sub_path":"flamby/datasets/fed_heart_disease/metric_fp.py","file_name":"metric_fp.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16774376773","text":"from functools import partial\nfrom glob import glob\nimport logging\nfrom multiprocessing.pool import Pool\nimport os\n\nimport cv2\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom mayo_clinic_strip_ai import utils\n\nlogger = logging.getLogger(__name__)\n\n\ndef process_file(image_id: str, input_dir: str, output_dir: str, downscale_factor) -> None:\n logger.info(f\"Starting on {image_id}...\")\n img = cv2.imread(os.path.join(input_dir, image_id + \".tif\"), cv2.IMREAD_COLOR)\n utils.validate_img(img)\n img = utils.downsize_img(img=img, downscale_factor=1 / downscale_factor)\n cv2.imwrite(filename=os.path.join(output_dir, image_id + \".jpeg\"), img=img)\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n\n if \"OPENCV_IO_MAX_IMAGE_PIXELS\" not in os.environ.keys():\n raise ValueError(\"Must set OPENCV_IO_MAX_IMAGE_PIXELS env var!\")\n\n parser = ArgumentParser()\n parser.add_argument(\"--input-filepath\", type=str)\n parser.add_argument(\"--input-dir\", type=str)\n parser.add_argument(\"--downscale-factor\", type=int)\n parser.add_argument(\"--output-dir\", type=str)\n parser.add_argument(\"--num-processes\", type=int)\n args = parser.parse_args()\n os.makedirs(args.output_dir, exist_ok=True)\n meta = pd.read_csv(args.input_filepath)[\"image_id\"]\n existing_image_ids = [f.split(\"/\")[-1].rstrip(\".jpeg\") for f in glob(os.path.join(args.output_dir, \"*.jpeg\"))]\n meta = meta[~meta.isin(existing_image_ids)]\n with Pool(processes=args.num_processes) as pool:\n pool.map(\n partial(\n process_file,\n input_dir=args.input_dir,\n output_dir=args.output_dir,\n downscale_factor=args.downscale_factor,\n ),\n tqdm(meta.tolist()),\n chunksize=1,\n )\n","repo_name":"schmidt-jake/kaggle","sub_path":"mayo_clinic_strip_ai/downsample.py","file_name":"downsample.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"32036928356","text":"from pyspark import SparkContext\nimport sys\nfrom operator import add\nimport re\n\nif __name__ == '__main__':\n def process(data):\n data = data.lower().replace(\"-\", \"\").replace(\"'\", \"\")\n data = re.sub(r'[^0-9a-zA-Z]', \" \", data)\n data = ' '.join(data.split())\n data = data.strip()\n return data\n\n sc = SparkContext(appName=\"inf553\")\n lines = sc.textFile(sys.argv[1])\n header = lines.first()\n\n results = lines.filter(lambda x: x != header) \\\n .map(lambda x: x.split(\",\")) \\\n .map(lambda p: (p[3], int(p[18]))) \\\n .map(lambda p: (process(p[0]), p[1])) \\\n .filter(lambda p: p[0] != '') \\\n .map(lambda p: (p[0],(p[1],1))) \\\n .reduceByKey(lambda U, x: (U[0]+x[0], U[1]+x[1])) \\\n .mapValues(lambda x: (x[1], (\"%.3f\" % ((x[0]*1.0)/x[1]))))\\\n .sortByKey()\\\n .map(lambda x: x[0] + \"\\t\" + str(x[1][0]) + \"\\t\" + str( x[1][1]))\n\n results.coalesce(1).saveAsTextFile(sys.argv[2])\n\n","repo_name":"xiaruolei/INF553","sub_path":"Assignment1/task2/Ruolei_Xia_Average.py","file_name":"Ruolei_Xia_Average.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33917044683","text":"import pygame\r\n\r\n# Some \"macros\"\r\n# --------------\r\nINF = 10 ** 6\r\n\r\nFREE = 0\r\nJERRY_INIT = 1\r\nJERRY_END = 2\r\nTOM_INIT = 3\r\n\r\nOBSTACLE0 = 4\r\nOBSTACLE1 = 5\r\nOBSTACLE2 = 6\r\nOBSTACLE3 = 7\r\n\r\nTRAP0 = 8\r\nTRAP1 = 9\r\nTRAP2 = 10\r\n\r\nC_FREE = (255, 255, 255)\r\nC_JI = (250, 2, 64)\r\nC_JE = (250, 110, 2)\r\nC_TI = (61, 0, 148)\r\n\r\nC_OBS0 = (0, 102, 12)\r\nC_OBS1 = (102, 24, 0)\r\nC_OBS2 = (232, 177, 104)\r\nC_OBS3 = (201, 162, 111)\r\n\r\nC_TR0 = (36, 255, 240)\r\nC_TR1 = (168, 94, 34)\r\nC_TR2 = (237, 36, 0)\r\n\r\n\r\n# ########################\r\n# # All entities go here #\r\n# ########################\r\nclass Entity:\r\n def __init__(self, x: int, y: int, sprite_path: str, w, m):\r\n self.x, self.y = x, y\r\n self.sprite = pygame.image.load(sprite_path)\r\n self.sprite = pygame.transform.scale(self.sprite, (w.get_width() // m.width, w.get_height() // m.height))\r\n\r\n self.dx = [1, -1, 0, 0]\r\n self.dy = [0, 0, 1, -1]\r\n\r\n def render(self, window, m):\r\n scaled_pos = (\r\n self.x * window.get_width() // m.width,\r\n self.y * window.get_height() // m.height\r\n )\r\n\r\n window.blit(self.sprite, scaled_pos)\r\n\r\n def get_pos(self):\r\n return tuple((self.x, self.y))\r\n\r\n \"\"\"Función para determinar si la dirección a la que la entidad se quiere desplazar es válida\"\"\"\r\n @staticmethod\r\n def valid(x: int, y: int, lista_cerrada, m):\r\n return \\\r\n (x >= 0) and \\\r\n (x < 7) and \\\r\n (y >= 0) and \\\r\n (y < 10) and \\\r\n (m.vals[x][y] != 4 and m.vals[x][y] != 5 and m.vals[x][y] != 6 and m.vals[x][y] != 7) and \\\r\n ((x, y) not in lista_cerrada)\r\n\r\n \"\"\"Algoritmo principal en el que se desarrolla la búsqueda de caminos.\"\"\"\r\n def A_estrella(self, m, init, destino, objetivo_peligro, entity):\r\n lista_cerrada = [init]\r\n padres = [[0 for _ in range(m.width)] for _ in range(m.height)]\r\n F = [[1000 for _ in range(m.width)] for _ in range(m.height)]\r\n G = [[0 for _ in range(m.width)] for _ in range(m.height)]\r\n\r\n while True:\r\n block = False\r\n x, y = lista_cerrada[-1]\r\n\r\n for i in range(4):\r\n nx = x + self.dx[i]\r\n ny = y + self.dy[i]\r\n\r\n if self.valid(nx, ny, lista_cerrada, m):\r\n if (x, y) == init:\r\n F[nx][ny] = 5 + entity.heuristica(m, [nx, ny], destino, objetivo_peligro)\r\n padres[nx][ny] = (x, y)\r\n elif (nx, ny) == destino:\r\n lista_cerrada.append((nx, ny))\r\n padres[nx][ny] = (x, y)\r\n else:\r\n G[nx][ny] = G[x][y] + 5\r\n F[nx][ny] = G[nx][ny] + entity.heuristica(m, [nx, ny], destino, objetivo_peligro)\r\n padres[nx][ny] = (x, y)\r\n\r\n if lista_cerrada[-1] == destino:\r\n break\r\n\r\n menor = min(map(min, F))\r\n # print(F, menor)\r\n for i in range(m.height):\r\n for j in range(m.width):\r\n if menor == F[i][j] and (i, j) not in lista_cerrada and not block:\r\n lista_cerrada.append((i, j))\r\n F[i][j] = 1000\r\n block = True\r\n\r\n return padres\r\n\r\n \"\"\"Punto de entrada de la IA de cada entidad.\"\"\"\r\n def algoritmo(self, m, init, destino, objetivo_peligro, entity):\r\n _inicio = (init[1], init[0])\r\n _destino = (destino[1], destino[0])\r\n _objetivo_peligro = (objetivo_peligro[1], objetivo_peligro[0])\r\n\r\n padres = self.A_estrella(m, _inicio, _destino, _objetivo_peligro, entity)\r\n recorrido = [_destino]\r\n x, y = _destino\r\n block = False\r\n\r\n while not block:\r\n for i in range(m.height):\r\n for j in range(m.width):\r\n if (i, j) == padres[x][y]:\r\n recorrido.append((i, j))\r\n if (i, j) == _inicio:\r\n block = True\r\n x, y = i, j\r\n\r\n recorrido.reverse()\r\n return recorrido\r\n\r\n\r\nclass Tom(Entity):\r\n def __init__(self, x: int, y: int, w, m):\r\n super().__init__(x, y, 'resources/tom.png', w, m)\r\n\r\n \"\"\"Heurística única para Tom. No le importa las trampas en el entorno, con tal de ir por la ruta más corta.\"\"\"\r\n @staticmethod\r\n def heuristica(m, pos, jerry_end, objetivo_peligro):\r\n heuristica = abs(pos[0] - jerry_end[0]) + abs(pos[1] - jerry_end[1])\r\n if m.vals[pos[0]][pos[1]] == 8 or m.vals[pos[0]][pos[1]] == 9 or m.vals[pos[0]][pos[1]] == 10:\r\n heuristica += 1\r\n return heuristica\r\n\r\n\r\nclass Jerry(Entity):\r\n def __init__(self, x: int, y: int, w, m):\r\n super().__init__(x, y, 'resources/jerry.png', w, m)\r\n\r\n \"\"\"Heurística única para Jerry. Con tal de llegar lo más rápido posible busca la ruta con menos trampas en ella.\"\"\"\r\n @staticmethod\r\n def heuristica(m, pos, jerry_end, objetivo_peligro):\r\n heuristica = abs(pos[0] - jerry_end[0]) + abs(pos[1] - jerry_end[1])\r\n if m.vals[pos[0]][pos[1]] == 8 or m.vals[pos[0]][pos[1]] == 9 or m.vals[pos[0]][pos[1]] == 10:\r\n heuristica += 100\r\n if abs(pos[0] - objetivo_peligro[0]) + abs(pos[1] - objetivo_peligro[1]) <= 2:\r\n heuristica += 200\r\n return heuristica\r\n\r\n\r\n# ########################\r\n# # Map class definition #\r\n# ########################\r\nclass Map:\r\n def __init__(self, tiles_vals: list):\r\n self.vals = tiles_vals\r\n self.width = len(self.vals[0])\r\n self.height = len(self.vals)\r\n\r\n # Validate the map\r\n ti_count, ji_count, je_count = 0, 0, 0\r\n i, j = 0, 0\r\n for row in self.vals:\r\n for column in row:\r\n if column == TOM_INIT:\r\n ti_count += 1\r\n elif column == JERRY_INIT:\r\n ji_count += 1\r\n elif column == JERRY_END:\r\n je_count += 1\r\n self.j_end = (j, i)\r\n j += 1\r\n i += 1\r\n assert ti_count == 1 and ji_count == 1 and je_count == 1\r\n\r\n \"\"\"Renderizar el mapa.\"\"\"\r\n def render(self, window):\r\n scr_w = window.get_width() // self.width\r\n scr_h = window.get_height() // self.height\r\n\r\n for y in range(self.height):\r\n for x in range(self.width):\r\n t = self.vals[y][x]\r\n\r\n color = \\\r\n C_FREE if t == FREE else \\\r\n C_JI if t == JERRY_INIT else \\\r\n C_JE if t == JERRY_END else \\\r\n C_TI if t == TOM_INIT else \\\r\n C_OBS0 if t == OBSTACLE0 else \\\r\n C_OBS1 if t == OBSTACLE1 else \\\r\n C_OBS2 if t == OBSTACLE2 else \\\r\n C_OBS3 if t == OBSTACLE3 else \\\r\n C_TR0 if t == TRAP0 else \\\r\n C_TR1 if t == TRAP1 else C_TR2\r\n\r\n pygame.draw.rect(window, color, (x * scr_w, y * scr_h, scr_w, scr_h))\r\n\r\n\r\n# ##############\r\n# # CORE class #\r\n# ##############\r\nclass Game:\r\n def __init__(self, wnd_resolution: tuple):\r\n pygame.init()\r\n\r\n \"\"\"MAPA 1\"\"\"\r\n map1 = [[3, 0, 7, 0, 6, 6, 0, 9, 0, 2],\r\n [8, 0, 7, 0, 0, 0, 0, 0, 0, 0],\r\n [0, 10, 7, 0, 5, 5, 5, 10, 10, 9],\r\n [8, 0, 7, 0, 0, 0, 0, 0, 0, 0],\r\n [0, 10, 7, 7, 7, 7, 7, 0, 0, 4],\r\n [0, 0, 4, 5, 5, 5, 4, 0, 0, 0],\r\n [0, 0, 0, 0, 0, 0, 0, 0, 9, 1]]\r\n\r\n \"\"\"MAPA 2\"\"\"\r\n map2 = [[3, 0, 8, 6, 6, 6, 4, 9, 0, 2],\r\n [0, 10, 0, 9, 0, 0, 0, 8, 0, 0],\r\n [4, 0, 7, 0, 5, 0, 7, 0, 0, 9],\r\n [5, 0, 7, 0, 5, 0, 7, 0, 10, 4],\r\n [5, 0, 0, 0, 5, 0, 0, 0, 0, 0],\r\n [5, 0, 7, 0, 0, 0, 7, 0, 9, 0],\r\n [4, 0, 7, 7, 7, 7, 7, 0, 0, 1]]\r\n\r\n \"\"\"MAPA 3\"\"\"\r\n map3 = [[ 3, 0, 4, 6, 6, 6, 4, 0, 0, 2],\r\n [ 0, 9, 10, 0, 0, 0, 10, 0, 0, 0],\r\n [10, 0, 7, 0, 5, 0, 7, 0, 4, 7],\r\n [ 0, 8, 0, 0, 5, 0, 0, 0, 7, 5],\r\n [ 0, 0, 7, 0, 5, 9, 7, 0, 0, 5],\r\n [ 0, 0, 0, 0, 0, 0, 10, 0, 7, 5],\r\n [ 4, 5, 4, 0, 1, 0, 9, 0, 4, 7]]\r\n\r\n self.window = pygame.display.set_mode(wnd_resolution)\r\n self.game_over = False\r\n self.jerry_wins = False\r\n self.map = Map(map3)\r\n\r\n selected = self.map.vals\r\n for i in range(len(selected)):\r\n for j in range(len(selected[0])):\r\n if selected[i][j] == 3:\r\n self.tom_ai = Tom(j, i, self.window, self.map)\r\n if selected[i][j] == 1:\r\n self.jerry_ai = Jerry(j, i, self.window, self.map)\r\n if selected[i][j] == 2:\r\n self.ratonera = (j, i)\r\n\r\n \"\"\"Punto de entrada del juego\"\"\"\r\n def run(self):\r\n def event_handler():\r\n for event in pygame.event.get():\r\n # Main exit event\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n exit()\r\n # Keyboard events\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_ESCAPE:\r\n exit()\r\n\r\n # Initialize\r\n # -----------\r\n pygame.display.set_caption(\"Tom & Jerry in...\")\r\n # pygame.display.set_icon(pygame.image.load(\"resources/icon.png\"))\r\n my_font = pygame.font.Font(None, 30)\r\n frame = 0\r\n # -----------\r\n j_end = [0, 0]\r\n for i in range(self.map.height):\r\n for j in range(self.map.width):\r\n if self.map.vals[i][j] == JERRY_END:\r\n j_end = [j, i]\r\n\r\n time = 2000\r\n cont = 0\r\n # Now actually run the game\r\n # --------------------------\r\n\r\n \"\"\"Mientras el juego no haya acabado...\"\"\"\r\n while not self.game_over:\r\n current_frame = pygame.time.get_ticks()\r\n self.window.fill((0, 0, 0))\r\n\r\n \"\"\"Si Tom llega a la casita de Jerry, o a Jerry, perdiste. En cambio, si Jerry llega primero, ganaste.\"\"\"\r\n if self.tom_ai.get_pos() == self.jerry_ai.get_pos() or \\\r\n self.tom_ai.get_pos() == self.map.j_end:\r\n self.game_over = True\r\n elif self.jerry_ai.get_pos() == self.map.j_end:\r\n self.jerry_wins = True\r\n self.game_over = True\r\n\r\n self.map.render(self.window)\r\n self.tom_ai.render(self.window, self.map)\r\n self.jerry_ai.render(self.window, self.map)\r\n\r\n if time <= 0 and cont == 0:\r\n t_pos = (self.tom_ai.x, self.tom_ai.y)\r\n j_pos = (self.jerry_ai.x, self.jerry_ai.y)\r\n self.tom_ai.y, self.tom_ai.x = self.tom_ai.algoritmo(self.map, t_pos, j_pos, (-1, -1), self.tom_ai)[1]\r\n time = 2000\r\n cont = 1\r\n\r\n if time <= 0 and cont == 1:\r\n t_pos = (self.tom_ai.x, self.tom_ai.y)\r\n j_pos = (self.jerry_ai.x, self.jerry_ai.y)\r\n self.jerry_ai.y, self.jerry_ai.x = \\\r\n self.jerry_ai.algoritmo(self.map, j_pos, j_end, t_pos, self.jerry_ai)[1]\r\n time = 2000\r\n cont = 0\r\n\r\n time -= 1\r\n\r\n event_handler()\r\n pygame.display.update()\r\n\r\n \"\"\"Render previo al cierre del programa...\"\"\"\r\n if self.jerry_wins:\r\n print(\"GANASTE!\")\r\n mensaje = my_font.render(\"GANASTE!\", False, (0, 0, 0))\r\n else:\r\n print(\"PERDISTE!\")\r\n mensaje = my_font.render(\"PERDISTE!\", False, (0, 0, 0))\r\n\r\n self.window.blit(mensaje, (self.window.get_width() // 2, self.window.get_width() // 2))\r\n pygame.display.update()\r\n pygame.time.delay(5 * 1000)\r\n pygame.quit()\r\n exit()\r\n # --------------------------\r\n\r\n\r\n# Punto de entrada del programa en sí\r\ndef main():\r\n tnj = Game((800, 600))\r\n tnj.run()\r\n\r\n\r\n# Inicializador\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"u201922331/IA_Tom_n_Jerry","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"74922593557","text":"import RPi.GPIO as gpio\nimport rospy\nfrom std_msgs.msg import Bool\n\nnode_name = \"load_cell_node\"\n\nclass LoadCellController:\n def __init__(self):\n rospy.init_node(node_name)\n rospy.loginfo(node_name + \" started\")\n self.pub = rospy.Publisher(\"load_cell/catch\", Bool, queue_size=10)\n\n self.DT = 27\n self.SCK = 17\n self.DRONE_WEIGHT = 135\n self.WEIGHT_DELIMETER = 283\n\n def readCount(self):\n i = 0\n Count = 0\n gpio.setup(self.DT, gpio.OUT)\n gpio.setup(self.SCK, gpio.OUT)\n gpio.output(self.DT, 1)\n gpio.output(self.SCK, 0)\n gpio.setup(self.DT, gpio.IN)\n\n while gpio.input(self.DT) == 1:\n i = 0\n for i in range(24):\n gpio.output(self.SCK, 1)\n Count = Count << 1\n\n gpio.output(self.SCK, 0)\n # time.sleep(0.001)\n if gpio.input(self.DT) == 0:\n Count = Count + 1\n\n gpio.output(self.SCK, 1)\n Count = Count ^ 0x800000\n gpio.output(self.SCK, 0)\n return Count\n\n def run(self):\n gpio.setmode(gpio.BCM)\n sample = self.readCount()\n try:\n r = rospy.Rate(5)\n while not rospy.is_shutdown():\n count = self.readCount()\n weight = (sample - count) / self.WEIGHT_DELIMETER\n print(weight)\n if weight >= self.DRONE_WEIGHT:\n self.pub.publish(True)\n # else:\n # self.pub.publish(False)\n r.sleep()\n except KeyboardInterrupt:\n rospy.signal_shutdown(\"Interrupted by keyboard\")\n\n\nif __name__ == '__main__':\n controller = LoadCellController()\n controller.run()\n\n\n\n\n","repo_name":"deadln/clover-interceptor-onboard","sub_path":"scripts/LoadCellController.py","file_name":"LoadCellController.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4595124777","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Author: xfc\n# @Time : 2019/11/14 17:52\n\n\n#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Author: xfc\n# @Time : 2019/11/14 17:34\nimport pymysql\nimport os\nimport time\nimport logging\n\nfrom common.utils import get_china_sse_spider_path\nfrom common.utils import get_china_szse_spider_path\nfrom common.utils import get_hongkong_spider_path\nfrom common.utils import get_table_name\nfrom common.utils import get_file_path\n\n\nclass CompanyValues:\n\n conn = pymysql.connect(host=\"10.100.4.99\", port=3306, db=\"opd_common\", user=\"root\", passwd=\"OPDATA\",\n charset=\"utf8\")\n cursor = conn.cursor()\n\n con = pymysql.connect(host='10.100.4.99', user='root', passwd='OPDATA', db='opd_common', charset='utf8')\n cur = conn.cursor(cursor=pymysql.cursors.DictCursor)\n\n def __init__(self):\n self.logger = logging.getLogger()\n self.root_path = os.path.abspath(os.path.dirname(__file__)).split('spiderItemV2')[0]\n self.logger_fh = logging.FileHandler(r'%s/LoggerUpdate.log'% self.root_path)\n self.logger_ch = logging.StreamHandler()\n\n self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n self.logger_fh.setFormatter(self.formatter)\n self.logger_ch.setFormatter(self.formatter)\n\n def readBase(self):\n sql = \"SELECT\" \\\n \" country_code, exchange_market_code, security_code, company_code, \" \\\n \"display_label, information, gmt_create, user_create \" \\\n \"FROM\" \\\n \" `{}` \" \\\n \"ORDER BY\" \\\n \" id \" \\\n \"ASC ;\"\n executavle_sql = sql.format(str(get_table_name()))\n try:\n self.cursor.execute(executavle_sql)\n feild_values = self.cursor.fetchall()\n return feild_values\n except Exception as e:\n return \"ERROR Reason Is : %s\" % e\n\n def lingResult(self):\n for unique in self.readBase():\n sql = \"SELECT\" \\\n \" * \" \\\n \"FROM\" \\\n \" `company_raw_info` \" \\\n \"WHERE\" \\\n \" company_code='{}' \" \\\n \"AND\" \\\n \" country_code='{}' \" \\\n \"AND\" \\\n \" exchange_market_code='{}' \" \\\n \"AND\" \\\n \" security_code='{}' \" \\\n \"AND\" \\\n \" display_label='{}' \" \\\n \"AND\" \\\n \" information='{}' \" \\\n \"ORDER BY\" \\\n \" security_code \" \\\n \"ASC ;\".format(\n unique[3],\n unique[0],\n unique[1],\n unique[2],\n unique[4],\n unique[5]\n )\n try:\n self.cur.execute(sql)\n if self.cur.execute(sql) == 0:\n self.insertdata(unique)\n self.logger.info(\"数据更新:%s,%s\" % (unique[4], unique[5]))\n else:\n pass\n\n except Exception as e:\n print(e)\n\n def insertdata(self, unique):\n item = {}\n item['company_code'] = unique[3]\n item['country_code'] = unique[0]\n item['exchange_market_code'] = unique[1]\n item['security_code'] = unique[2]\n item['display_label'] = unique[4]\n item['information'] = unique[5]\n item['gmt_create'] = str(unique[6])\n item['user_create'] = unique[7]\n cols, values = zip(*item.items())\n sql = \"INSERT INTO `{}` ({}) VALUES {}\".format \\\n (\n 'company_raw_info',\n ','.join(cols),\n (str(values) + ',')[0:-1]\n )\n self.logger.info(sql)\n try:\n self.cursor.execute(sql)\n self.conn.commit()\n\n except Exception as e:\n self.logger.info(\"ERROR IS %s\" % e)\n\n\nif __name__ == '__main__':\n keys = CompanyValues()\n keys.lingResult()\n","repo_name":"waynecanfly/spiderItemV2","sub_path":"common/compare_values.py","file_name":"compare_values.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"39558445600","text":"def main():\n numbers, boards = get_data('input.txt')\n\n # Result 1\n score = pick_numbers(numbers, boards)\n print(score)\n\n # Result 2\n min_case_score = last_board(numbers, boards)\n print(min_case_score)\n\ndef get_data(filename):\n with open(filename) as file:\n data = file.read().split('\\n\\n')\n numbers = data[0].split(',')\n boards = [board.split('\\n') for board in data[1:]]\n \n for board in boards:\n for i in range(len(board)):\n board[i] = board[i].split()\n \n return numbers, boards\n\n\ndef pick_numbers(numbers, boards):\n for i in range(len(numbers)):\n if check_win(numbers[:i], boards): break\n \n nums, brd = check_win(numbers[:i], boards)\n return calculate_score(nums, brd)\n\n\ndef last_board(numbers, boards):\n won_boards = []\n idx = None\n\n for i in range(len(numbers)):\n if len(won_boards) == len(boards) - 1:\n idx = i; break\n\n for board in boards:\n rows = board\n cols = [[x[i] for x in rows] for i in range(len(board))]\n\n for row in rows:\n if set(row) <= set(numbers[:i]) and board not in won_boards: won_boards.append(board)\n\n for col in cols:\n if set(col) <= set(numbers[:i])and board not in won_boards: won_boards.append(board)\n \n diff = [x for x in boards if x not in won_boards]\n \n return calculate_score(numbers[:idx], diff[0])\n\n \ndef check_win(numbers, boards):\n for board in boards:\n rows = board\n cols = [[x[i] for x in rows] for i in range(len(board))]\n\n for row in rows:\n if set(row) <= set(numbers): return numbers, board\n\n for col in cols:\n if set(col) <= set(numbers): return numbers, board\n\n\ndef calculate_score(numbers, board):\n som = 0\n\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] not in numbers:\n som += int(board[i][j])\n \n return som * int(numbers[-1])\n\nif __name__ == '__main__':\n main()","repo_name":"Max-Verbinnen/AdventOfCode","sub_path":"2021/Day 04/day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32300099201","text":"from aiogram import Bot, Dispatcher\nfrom aiogram.fsm.storage.redis import RedisStorage, Redis\n\nfrom config.config import Config, load_config\nfrom keyboards.set_menu import set_main_menu\n\nimport handlers\n\n\nasync def main() -> None:\n configuration: Config = load_config(\".env\")\n\n BOT_TOKEN: str = configuration.tg_bot.token\n\n redis = Redis(\n host=configuration.db.redis_host,\n port=configuration.db.redis_port,\n db=configuration.db.redis_db,\n )\n\n bot: Bot = Bot(token=BOT_TOKEN, parse_mode=\"html\")\n\n storage = RedisStorage(redis=redis)\n\n dp: Dispatcher = Dispatcher(bot=bot, configuration=configuration, storage=storage)\n\n dp.startup.register(set_main_menu)\n\n dp.include_router(handlers.admin_handlers.router)\n dp.include_router(handlers.user_handlers.router)\n dp.include_router(handlers.form_handlers.router)\n dp.include_router(handlers.other_handlers.router)\n\n await bot.delete_webhook(drop_pending_updates=True)\n await dp.start_polling(bot)\n","repo_name":"BLazzeD21/py-aiogram-template-bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"2812615202","text":"import codecs\nimport os \n\ndef compute_ham(string1, string2):\n # Check if strings are equal length\n if len(string1) != len(string2):\n return None\n\n # Convert string to bits\n if type(string1) == bytes: \n bit_string1 = ''.join([bin(x)[2:].zfill(8) for x in string1])\n else:\n bit_string1 = ''.join([bin(ord(x))[2:].zfill(8) for x in string1])\n \n if type(string2) == bytes: \n bit_string2 = ''.join([bin(x)[2:].zfill(8) for x in string2])\n else:\n bit_string2 = ''.join([bin(ord(x))[2:].zfill(8) for x in string2])\n\n # Compute hamming distance\n count = 0 \n for index, value in enumerate(bit_string1):\n count += 0 if value == bit_string2[index] else 1\n\n # Return hamming distance\n return count\n\ndef return_likey_xor_key_length(KEYSIZES, message):\n distances = dict()\n\n for key in KEYSIZES:\n one = message[:key]\n two = message[key:key*2]\n three = message[key*2:key*3]\n four = message[key*3:key*4]\n #distances[key] = compute_ham(one, two)/key\n distances[key] = (compute_ham(one, two)/key + compute_ham(two, three)/key + compute_ham(three, four)/key)/3\n\n return dict(sorted(distances.items(), key = lambda x: x[1])[:3])\n\ndef solve_single_XOR(block):\n # get all characters it could have been XORed with \n characters = [i for i in range(128)] \n \n # My original code for doing this \n # letters = [chr(i) for i in range(65, 91)] # do chr(i) to get the letters\n # letters = letters + [chr(i) for i in range(97, 123)]\n # letters2 = [chr(i) for i in range(32, 128)]\n\n character_frequencies = {\n 'a': .08167, 'b': .01492, 'c': .02782, 'd': .04253,\n 'e': .12702, 'f': .02228, 'g': .02015, 'h': .06094,\n 'i': .06094, 'j': .00153, 'k': .00772, 'l': .04025,\n 'm': .02406, 'n': .06749, 'o': .07507, 'p': .01929,\n 'q': .00095, 'r': .05987, 's': .06327, 't': .09056,\n 'u': .02758, 'v': .00978, 'w': .02360, 'x': .00150,\n 'y': .01974, 'z': .00074, ' ': .13000\n }\n \n # Save all possible options in a dictonary\n outcomes = dict()\n\n for ch in characters:\n # XOR with character\n attempt = [x ^ ch for x in block]\n \n # score = sum([1 if chr(item) in letters else 0 for item in attempt])\n # score = sum([1 if chr(item) in letters2 else 0 for item in attempt])\n # score = sum([1 if chr(item).upper() in ['E', 'A', 'I', 'O'] else 0 for item in attempt])\n\n score = sum([character_frequencies.get(chr(byte).lower(), 0) for byte in attempt])\n\n outcomes[f'{chr(ch)}'] = score\n\n # Return item with highest score:\n return max(outcomes, key=outcomes.get)\n\ndef repeating_key_XOR(message, key):\n \n message_ord = [x for x in message] if type(message[0]) == int else [ord(x) for x in message]\n key_ord = [x for x in key] if type(key[0]) == int else [ord(x) for x in key]\n index = 0\n decoded = list()\n\n for x in message_ord:\n if index < len(key_ord):\n decoded.append(chr(x ^ key_ord[index]))\n index += 1 \n else:\n decoded.append(chr(x ^ key_ord[0]))\n index = 1 \n return ''.join([str(x) for x in decoded])\n\ndef break_repeating_key_XOR(message):\n\n KEYSIZES = [x for x in range(2, 41)]\n key_lengths = return_likey_xor_key_length(KEYSIZES, message).keys()\n # Key length is most likely 29\n\n for length in key_lengths:\n split_message = [message[i:i+length] for i in range(0, len(message), length)]\n blocks = list()\n\n for index in range(0, length):\n # blocks.append([x[index] for x in split_message])\n transpose = list()\n\n for char_block in split_message:\n try:\n transpose.append(char_block[index])\n except IndexError:\n continue\n\n blocks.append(transpose)\n \n key_list = [solve_single_XOR(block) for block in blocks]\n key = ''.join(key_list)\n \n print()\n print(f'Key == {key}')\n print(repeating_key_XOR(message, key))\n\n\ndef main():\n message = open(os.path.join(os.getcwd(), 'Input/Set1/Input 6.txt'), 'rb').read()\n message = codecs.decode(message, 'base64')\n\n\n # print(compute_ham(\"this is a test\", \"wokka wokka!!!\"))\n # 37\n \n break_repeating_key_XOR(message)\n \n\nif __name__ == '__main__':\n main()\n","repo_name":"Hungry-Dolphin/Cryptopals-crypto-challenges","sub_path":"Set1/Challenge 6.py","file_name":"Challenge 6.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18255781459","text":"#Source script from torch, data loader\n#Modified to our goal\nfrom __future__ import print_function, division\nimport os\nimport torch\nimport json\nfrom torch.utils.data import Dataset\nfrom CLIPyourFood.Data.utils import lables2vec,TRANSFORMS\nfrom PIL import Image\n\n\n\nclass IngredientsDataset(Dataset):\n \"\"\"Ingredients dataset.\"\"\"\n\n def __init__(self, json_file, root_dir, transform=TRANSFORMS, img_ext='.jpg'):\n \"\"\"\n\t\tArgs:\n\t\t\tjson_file (string): Path to the json file with annotations.\n\t\t\troot_dir (string): Directory with all the images.\n\t\t\ttransform (callable, optional): Optional transform to be applied\n\t\t\t\ton a sample.\n\t\t\"\"\"\n with open(json_file) as json_data:\n self.ingredients_frame = json.load(json_data)\n self.root_dir = root_dir\n self.transform = transform\n self.images = list(self.ingredients_frame.keys())\n self.img_ext = img_ext\n\n def __len__(self):\n return len(self.images)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n img_name = self.images[idx]\n img_path = os.path.join(self.root_dir,'images', img_name + self.img_ext)\n image = Image.open(img_path)\n image = image.convert('RGB')\n ingredients_names = self.ingredients_frame[img_name][0]\n dish_name = self.ingredients_frame[img_name][1]\n dish_info = (img_path, dish_name)\n ingredients_vec = lables2vec(ingredients_names, os.path.join(self.root_dir,'meta',\n 'ingredients_dict.txt'))\n\n if self.transform:\n image = self.transform(image)\n\n return image, ingredients_vec, dish_info\n","repo_name":"KhaBetty/CLIPyourFood","sub_path":"Data/IngredientsLoader.py","file_name":"IngredientsLoader.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30231782419","text":"class Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n graph = defaultdict(list)\n for start, end in roads:\n graph[start].append(end)\n graph[end].append(start)\n answer = 0\n for i in range(n):\n for j in range(i + 1, n):\n iset = set([(i, x) for x in graph[i]])\n jset = set([(j, x) for x in graph[j] if x != i])\n answer = max(len(iset) + len(jset), answer)\n return answer\n","repo_name":"park-jihoo/Algorithm","sub_path":"leetcode/Medium/1615-maximal-network-rank/1615-maximal-network-rank.py","file_name":"1615-maximal-network-rank.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"85"} +{"seq_id":"28449135650","text":"from rest_framework import serializers\nfrom projects.models import Project, Tag, Review\nfrom users.models import Profile\n\n# Add the models to serialize to json. This is accually like the form.py implementations.\nclass ProfileSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Profile\n fields = '__all__'\n\nclass TagSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Tag\n fields = '__all__'\n\nclass ReviewSerializers(serializers.ModelSerializer):\n class Meta:\n model = Review\n fields = '__all__'\n\n# reach objects that are many to many fields.\nclass ProjectSerializers(serializers.ModelSerializer):\n owner = ProfileSerializer(many=False)\n tags = TagSerializer(many=True)\n reviews = serializers.SerializerMethodField()\n\n class Meta:\n model = Project\n fields = '__all__'\n\n # A method in a serializer object always starts with a get_\n def get_reviews(self, obj):\n reviews = obj.review_set.all()\n serializer = ReviewSerializers(reviews, many=True)\n return serializer.data\n","repo_name":"Egelbalken/imonitcv","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1176355357","text":"import pandas as pd\n\nfrom create_database.models import connect_db\n\nengine = connect_db() # establish connection\nconnection = engine.connect()\n\n\ndef get_diff_atc():\n \"\"\"\n Lister les classes ATC qui ne sont pas identiques\n pour une même spécialité dans la table ruptures_dc et dans la table ventes\n :return: génère un csvc\n \"\"\"\n dfr = pd.read_sql_table(\"ruptures_dc\", connection)\n dfv = pd.read_sql_table(\"ventes\", connection)\n\n a = dfr.groupby([\"specialite\", \"atc\"]).count().reset_index()[[\"specialite\", \"atc\"]]\n a = a.rename(columns={\"atc\": \"atc_ruptures\"})\n\n b = (\n dfv.groupby([\"cis\", \"denomination_specialite\", \"atc\"])\n .count()\n .reset_index()[[\"cis\", \"denomination_specialite\", \"atc\"]]\n )\n b = b.rename(\n columns={\"denomination_specialite\": \"specialite_ventes\", \"atc\": \"atc_ventes\"}\n )\n\n c = pd.merge(a, b, left_on=\"specialite\", right_on=\"specialite_ventes\", how=\"outer\")\n c = c.where(pd.notnull(c), None)\n\n d = c[\n c.apply(\n lambda x: x.atc_ruptures != x.atc_ventes\n if (x.atc_ruptures and x.atc_ventes and x.specialite_ventes)\n else False,\n axis=1,\n )\n ]\n d = d.drop([\"specialite_ventes\"], axis=1)\n d = d[[\"cis\", \"specialite\", \"atc_ruptures\", \"atc_ventes\"]]\n d.to_csv(\"/Users/ansm/Desktop/diff_atc_ruptures_ventes.csv\", sep=\";\")\n","repo_name":"lrahal/datamed","sub_path":"analysis/check_atc.py","file_name":"check_atc.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"960886352","text":"#!/usr/bin/python3\n\"\"\"Function that queries the Reddit API to return the no. of subscribers\nfor a given subreddit.\"\"\"\nimport requests\n\n\ndef number_of_subscribers(subreddit):\n \"\"\"Returns the no. of subscribers\"\"\"\n url = \"https://www.reddit.com/r/{}/about.json\".format(subreddit)\n headers = {'User-Agent': 'Python/requests'}\n req = requests.get(url, headers=headers, allow_redirects=False)\n\n try:\n resp = req.json()\n return resp.get(\"data\", {}).get(\"subscribers\", 0)\n except Exception:\n return 0\n","repo_name":"emukus/alx-system_engineering-devops","sub_path":"0x16-api_advanced/0-subs.py","file_name":"0-subs.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20199045364","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.logging import util\nfrom googlecloudsdk.calliope import arg_parsers\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.calliope import exceptions as calliope_exceptions\n\nDETAILED_HELP = {\n 'DESCRIPTION': \"\"\"\n Updates the properties of a view.\n \"\"\",\n 'EXAMPLES': \"\"\"\n To update a view in your project, run:\n\n $ {command} my-view --bucket=my-bucket --location=global\n --description=my-new-description\n \"\"\",\n}\n\n\nclass Update(base.UpdateCommand):\n \"\"\"Update a view.\n\n Changes one or more properties associated with a view.\n \"\"\"\n\n @staticmethod\n def Args(parser):\n \"\"\"Register flags for this command.\"\"\"\n parser.add_argument(\n 'VIEW_ID', help='Id of the view to update.')\n parser.add_argument(\n '--description',\n help='New description for the view.')\n parser.add_argument(\n '--log-filter',\n help='New filter for the view.')\n util.AddParentArgs(parser, 'view to update')\n util.AddBucketLocationArg(\n parser, True, 'Location of the bucket that contains the view.')\n parser.add_argument(\n '--bucket', required=True,\n type=arg_parsers.RegexpValidator(r'.+', 'must be non-empty'),\n help='ID of the bucket that holds the view')\n\n def Run(self, args):\n \"\"\"This is what gets called when the user runs this command.\n\n Args:\n args: an argparse namespace. All the arguments that were provided to this\n command invocation.\n\n Returns:\n The updated view.\n \"\"\"\n view_data = {}\n update_mask = []\n parameter_names = ['--log-filter', '--description']\n if args.IsSpecified('log_filter'):\n view_data['filter'] = args.log_filter\n update_mask.append('filter')\n if args.IsSpecified('description'):\n view_data['description'] = args.description\n update_mask.append('description')\n\n if not update_mask:\n raise calliope_exceptions.MinimumArgumentException(\n parameter_names,\n 'Please specify at least one property to update')\n\n return util.GetClient().projects_locations_buckets_views.Patch(\n util.GetMessages().LoggingProjectsLocationsBucketsViewsPatchRequest(\n name=util.CreateResourceName(util.CreateResourceName(\n util.CreateResourceName(\n util.GetProjectResource(args.project).RelativeName(),\n 'locations',\n args.location),\n 'buckets', args.bucket), 'views', args.VIEW_ID),\n logView=util.GetMessages().LogView(**view_data),\n updateMask=','.join(update_mask)))\n\nUpdate.detailed_help = DETAILED_HELP\n","repo_name":"google-cloud-sdk-unofficial/google-cloud-sdk","sub_path":"lib/surface/logging/views/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"85"} +{"seq_id":"36453892221","text":"# -*- coding: utf-8 -*-\n__author__ = \"Konstantin Klementiev\"\n__date__ = \"31 Mar 2022\"\n# !!! SEE CODERULES.TXT !!!\n\n\ndef format_memory_size(size, decimals=1):\n for unit in ['B', 'kB', 'MB', 'GB', 'TB', 'PB']:\n if size < 1024 or unit == 'PB':\n break\n size /= 1024.0\n return f\"{size:.{decimals}f} {unit}\"\n","repo_name":"kklmn/ParSeq","sub_path":"parseq/utils/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"40918775910","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom ArDa.layouts.layout_filter_dialog import Ui_Dialog\nimport pandas as pd\nimport pdb\n\nclass FilterDialog(QtWidgets.QDialog):\n def __init__(self, parent_window, init_filter_field, doc_id_subset = None):\n # Initializing the dialog and the layout\n super().__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n\n # Setting class level variables\n self.parent_window = parent_window\n self.doc_id_subset = doc_id_subset\n\n # Set combo box to initial field value and connect to listener\n self.ui.comboBox_Field.setCurrentText(init_filter_field)\n self.ui.comboBox_Field.currentIndexChanged.connect(self.fieldChanged)\n\n # Set up the base model and filtering model behind the list view\n self.qsfp_model = QtCore.QSortFilterProxyModel()\n self.list_model = QtGui.QStandardItemModel(self.ui.listView_FilterVals)\n self.qsfp_model.setSourceModel(self.list_model)\n self.ui.listView_FilterVals.setModel(self.qsfp_model)\n\n # Connect the serach field to the proxy model (and make case insensitive)\n self.ui.lineEdit_Search.textChanged.connect(self.qsfp_model.setFilterRegExp)\n self.qsfp_model.setFilterCaseSensitivity(0) # 0 = insensitive, 1 = sensitive\n\n self.ui.lineEdit_Search.setFocus()\n\n # Populate the list widet with the choices\n self.populateListValues(init_filter_field)\n\n # Connecting the ok/cancel buttons (so they do more than just close the window)\n self.ui.buttonBox.accepted.connect(self.acceptSelection)\n self.ui.buttonBox.rejected.connect(self.rejectSelection)\n\n def fieldChanged(self):\n # This function repopulates the list values\n self.populateListValues(self.ui.comboBox_Field.currentText())\n\n def populateListValues(self, field_value):\n # This function populates all the values in the list view\n if field_value == \"Author\":\n # Grab all the full names from the doc_auth table\n self.temp_df = self.parent_window.adb.get_table(\"Doc_Auth\")\n if self.doc_id_subset != None:\n self.temp_df = self.temp_df[self.temp_df['doc_id'].isin(self.doc_id_subset)]\n series_vals = self.temp_df['full_name']\n elif field_value == \"Journal\":\n # Grab all the journal names from the documents table\n self.temp_df = self.parent_window.adb.get_table(\"Documents\")\n if self.doc_id_subset != None:\n self.temp_df = self.temp_df[self.temp_df['doc_id'].isin(self.doc_id_subset)]\n series_vals = self.temp_df['journal']\n elif field_value == \"Keyword\":\n # Grab all the keywords from the documents table\n self.temp_df = self.parent_window.adb.get_table(\"Documents\")\n if self.doc_id_subset != None:\n self.temp_df = self.temp_df[self.temp_df['doc_id'].isin(self.doc_id_subset)]\n series_vals = self.temp_df['keyword'].dropna()\n series_vals = pd.Series([elt for list_ in series_vals.str.split(\";\") for elt in list_])\n else:\n print(f\"Filter field ({field_value}) was not recognized.\")\n return\n\n # Deduplicating and sorting the values\n val_list = series_vals.drop_duplicates()\n val_list = val_list.loc[val_list.str.lower().sort_values().index]\n\n # Clearing list and adding new items to the list model (and thus view)\n self.list_model.clear()\n for val in val_list:\n item = QtGui.QStandardItem(val)\n self.list_model.appendRow(item)\n\n def acceptSelection(self):\n self.parent_window.filter_field = self.ui.comboBox_Field.currentText()\n self.parent_window.filter_choices = [str(x.data()) for x in \\\n self.ui.listView_FilterVals.selectionModel().selectedRows()]\n # self.parent_window.filter_choices = [str(x.text()) for x in \\\n # \t\t\t\t\t\t\tself.ui.listWidget.selectedItems()]\n\n def rejectSelection(self):\n return # Nothing else is done for the time being\n","repo_name":"elansegarra/ArDa","sub_path":"lib/ArDa/dialog_filter.py","file_name":"dialog_filter.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2832868118","text":"def solution(board, moves):\n answer = 0; result = []\n for i in moves:\n for j in range(0,len(board)):\n x = board[j][i-1]\n if x == 0 : continue\n result.append(x)\n board[j][i-1] = 0\n break\n \n if len(result)>1 and result[-1]==result[-2]: \n del result[-2:]\n answer += 2\n \n return answer","repo_name":"dlekdlsll/Programmers","sub_path":"crane_machine.py","file_name":"crane_machine.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"17683185275","text":"from aiogram import Dispatcher\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.types import Message\n\nfrom tgbot.keyboards.reply import accountKeyboard, keyboardBack, menuKeyBoardAuthorizated\nfrom tgbot.misc.api import api\nfrom tgbot.misc.states import StatesOfMenu, PersonalAccount\n\n\nasync def startAccount(message: Message):\n await StatesOfMenu.personalAccount.set()\n await message.answer(\"Добро пожаловать в личный кабинет!\",\n reply_markup=accountKeyboard)\n\n\nasync def ordersHistory(message: Message, state: FSMContext):\n await PersonalAccount.ordersHistory.set()\n data = await state.get_data()\n userPhoneNumber = data['userLogin']\n user = api.getUserByPhoneNumber(userPhoneNumber)\n orders = api.getOrdresByUserId(user.id)\n orderHistory: str\n if len(orders) == 0:\n await message.answer(\"Список заказов пуст\",\n reply_markup=keyboardBack)\n else:\n for order in orders:\n capsule = api.getCapsuleById(order.capsuleId)\n dateStartUsing = order.deliveryDateToClient.split(\"T\")\n dateStartUsing = dateStartUsing[0] + \", \" + dateStartUsing[1][0:4]\n orderHistory = f\"Заказ №{order.id}\\n\" \\\n f\"Стиль: {capsule.type}\" \\\n f\"Размер капсулы: {capsule.size}\" \\\n f\"Цена: {order.price}\" \\\n f\"Дата начала использования: {dateStartUsing}\"\n await message.answer(orderHistory,\n reply_markup=keyboardBack)\n\n\nasync def subscribeStatus(message: Message, state: FSMContext):\n # все статусы для заказа\n statuses = {'NEW': 'оформлена', 'COLLECT': 'капсула собирается', 'COLLECTED': 'капсула собрана',\n 'WITH_COURIER': 'капсула передана курьеру', 'WITH_CLIENT': 'вещи у вас',\n 'CANCELED': 'подписка не активна'}\n await PersonalAccount.subscribeStatus.set()\n data = await state.get_data()\n user = api.getUserByPhoneNumber(data['userLogin'])\n subscribe = api.getCurrentUserSubscribe(user.id)\n if subscribe is None:\n await message.answer(\"Вы еще не пользовались нашей подпиской, попробуйте!\",\n reply_markup=keyboardBack)\n else:\n await message.answer(f\"Статус подписки: {statuses[subscribe.status]}\",\n reply_markup=keyboardBack)\n\n\nasync def backFromSubStatusOrodHist(message: Message, state: FSMContext):\n await StatesOfMenu.personalAccount.set()\n await message.answer(\"Личный кабинет\",\n reply_markup=accountKeyboard)\n\nasync def backFromPersonalAccount(message: Message):\n await StatesOfMenu.menu.set()\n await message.answer(\"Меню\",\n reply_markup=menuKeyBoardAuthorizated)\n\n\ndef register_account(dp: Dispatcher):\n dp.register_message_handler(startAccount, text=\"Личный кабинет\", state=StatesOfMenu.menu)\n dp.register_message_handler(ordersHistory, text=\"История заказов\", state=StatesOfMenu.personalAccount)\n dp.register_message_handler(subscribeStatus, text=\"Статус подписки\", state=StatesOfMenu.personalAccount)\n dp.register_message_handler(backFromSubStatusOrodHist, text=\"Назад\", state=PersonalAccount)\n dp.register_message_handler(backFromPersonalAccount, text=\"Назад\", state=StatesOfMenu.personalAccount)\n\n","repo_name":"CodingByLegs/YellowHouse_clothing-subscription","sub_path":"tgbot/handlers/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19550489121","text":"import sys\n\nimport PyQt5.QtWidgets as qtw\nimport PyQt5.QtGui as qtg\n\nclass MainWindow(qtw.QWidget):\n def __init__(self):\n super().__init__()\n\n #Add a title\n self.setWindowTitle('Hello world')\n\n #set vertical layout \n self.setLayout(qtw.QVBoxLayout())\n\n #create a label\n self.my_label = qtw.QLabel(\"Hello world What's your name?\")\n \n self.layout().addWidget(self.my_label)\n\n #Change font size of label\n self.my_label.setFont(qtg.QFont('Helvetica', 18))\n\n # Create an entry box\n self.my_entry = qtw.QLineEdit()\n self.my_entry.setObjectName('name_field')\n self.my_entry.setText(\"\")\n self.layout().addWidget(self.my_entry)\n\n #Create a button \n my_button = qtw.QPushButton('Press me!', \n clicked=lambda:self.press_it())\n self.layout().addWidget(my_button)\n\n #show the app\n self.show()\n\n def press_it(self):\n #Add name to text\n self.my_label.setText(f'Hello {self.my_entry.text()}')\n #Clear the entry box\n self.my_entry.setText('')\n\n\n\nif __name__ == '__main__':\n app = qtw.QApplication(sys.argv)\n mw = MainWindow()\n\n app.exec_()","repo_name":"DmitryAsdre/PyQtLessons","sub_path":"lesson_0_hello_world.py","file_name":"lesson_0_hello_world.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9830991982","text":"from selenium.webdriver.common.by import By\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver import ActionChains\nfrom JobElement import JobElement\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import ElementNotInteractableException\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom UseDatabase import UseDatabase\nfrom VirtualUser import VirtualUser\nfrom Field import Field\nfrom HTMLExtractor import HTMLExtractor\nimport copy\nimport asyncio\nimport json\nimport time\n\ndbconfig = {\n 'user': 'root',\n 'password': '3dLIaPIdB3n3d1c',\n 'host': '127.0.0.1',\n 'database': 'jobs_search'\n}\n\n\nclass Page:\n \"\"\" Class that handles parsing and result processsing actions\"\"\"\n\n def __init__(self, driver, link):\n self.driver = driver\n self.virtualUser = VirtualUser(self.driver)\n self.done = False\n self.driver.maximize_window()\n self.driver.get(link)\n self.run()\n\n def run(self):\n self._do_setup()\n while self.done != True:\n self.navigate_to_searchable_state()\n \n def navigate_to_searchable_state(self):\n self.perform_search()\n\n jobs_list = self.driver.find_elements_by_xpath('//ul[contains(@class, \"jlGrid\")]/li')\n\n once = True\n\n for job in jobs_list:\n link = job.find_element_by_xpath('.//div/a')\n link.click()\n if once:\n self.do_once()\n once = False\n self.extractHTML()\n\n def do_once(self):\n try:\n overlay = self.virtualUser.wait.until(lambda d: d.find_element_by_css_selector('.modal_closeIcon'))\n overlay.click()\n except:\n print('overlay should be closed f')\n\n def _do_setup(self):\n self.virtualUser.do_gmail_login()\n\n def _get_loading_element(self, locator):\n element = self.virtualUser.wait.until(EC.element_to_be_clickable(\n (locator['by'], locator['value'])))\n return element\n\n def perform_search(self):\n keywordsElement = self._get_loading_element(\n {'by': By.ID, 'value': 'sc.keyword'})\n locationElement = self._get_loading_element(\n {'by': By.ID, 'value': 'sc.location'})\n self.keywordsField = Field(keywordsElement)\n self.locationField = Field(locationElement)\n self.actionBtn = self._get_loading_element(\n {'by': By.CSS_SELECTOR, 'value': '.SearchStyles__newSearchButton'})\n self.virtualUser.perform_search(\n self.keywordsField, self.locationField, self.actionBtn)\n\n def _get_element(self, selector):\n el = self.driver.find_element(selector['by'], selector['value'])\n return el\n\n def interact_handler(self, selector):\n try:\n el = self.driver.find_element(selector['by'], selector['value'])\n self.handleElementInteraction(el)\n except ElementNotInteractableException:\n print('Element not interactable or doesn\\'t exist')\n except NoSuchElementException:\n print('No such element exception')\n\n def handleElementInteraction(self, element):\n element.click()\n\n def extractHTML(self):\n self.virtualUser.wait.until(EC.presence_of_element_located((By.ID, \"JDWrapper\")))\n self.virtualUser.wait.until(EC.presence_of_element_located((By.ID, \"HeroHeaderModule\")))\n page_source = self.driver.page_source\n extractor = HTMLExtractor(page_source)\n fields = extractor.extract()\n print(fields)\n\n\n def save_to_database(self, JobsData):\n for job in JobsData:\n with UseDatabase(dbconfig) as cursor:\n _SQL = \"\"\"INSERT INTO job_list \n (company_name, job_title, location, posted_on, infoHTML, apply_link) \n VALUES(%s, %s, %s, %s, %s, %s)\"\"\"\n val = (job.company_name, job.job_title,\n job.location, job.posted_on, job.infoHTML, job.apply_link)\n cursor.execute(_SQL, val)\n","repo_name":"Eduard-Benedic/j_stats","sub_path":"Page.py","file_name":"Page.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"12809029019","text":"# Welcome to this tutorial on regular expressions in Python. The syntax will be explained with examples that you can modify and execute.\n\n# First, we need to import the regex module.\nimport re\n\n# Let's say we want to find every mention of a money amount in dollars in a passage. Unfortunately the author is very inconsistent, \n# so we need to search for different formats, such as all of these examples: \"$10, 7 dollars, two dollars, and $4.75.\"\n# Here is our sample text. Let's make things easy by putting it into a string to begin with:\nsample_text = \"\"\"\nI went to the store with 10 dollars in my pocket. I bought milk for $2.50. I bought bread for $1 and cheese for two dollars.\"\"\" \n\n# So, we want a regex to give us this list: \n# [\"10 dollars\", \"$2.50\", \"$1\", \"two dollars\"]\n\n# We first want to create a variable using re.compile(r\"\"). Raw strings (the r) are used so we can use \\ without escaping.\n# Let's start simple and just find everything in quotes.\nour_regex_pattern = re.compile(r'\"(.*?)\"')\n\n# Now we can search our string and store the results in a match object. We use the find all to get a list of all matches.\nmatch_object = our_regex_pattern.findall(sample_text)\n\nprint(match_object)\n","repo_name":"SoheebAmin/Website_Tutorial","sub_path":"regex_explainer.py","file_name":"regex_explainer.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1756354329","text":"\"\"\" PirSensor class for encapsulating the interaction with proximity\nsensor.\n\"\"\"\n\nimport time\n\nREPORT_FREQUENCY = 10 * 60 # FREQ = minutes * 60 sec / minute\n\nclass PirSensor(object):\n # Initialize class variables here\n\n def __init__(self, gpio_obj, led_pin):\n # Initialize instance variables here\n # Prefix with two underscores for private.\n self.__start_rise = 0.0\n self.__number_of_rises = 0\n self.__seconds_at_high = 0.0\n self.__next_report = 0.0\n self.__led_pin = led_pin\n self.__gpio = gpio_obj\n\n def process_edge(self, gpio, level, tick):\n time_last_sense = 0.0\n current_time = time.time()\n time_since_rise = 0.0\n\n if level:\n if self.__next_report == 0.0:\n self.__next_report = current_time + REPORT_FREQUENCY\n print('Setting initial report time - %20.2f' %\n (self.__next_report))\n self.__gpio.write(self.__led_pin, 1)\n print('PirSensor rising')\n self.__start_rise = time.time()\n self.__number_of_rises += 1\n self.__start_rise = current_time\n else:\n self.__gpio.write(self.__led_pin, 0)\n print('PirSensor falling')\n if self.__start_rise > 0.0:\n time_since_rise = current_time - self.__start_rise\n self.__seconds_at_high = self.__seconds_at_high \\\n + time_since_rise\n print('Time at high is %6.2f' % time_since_rise)\n\n print('Next report at %s' % (time.asctime(\n time.localtime(self.__next_report))))\n print('Current time %s' % (time.asctime(\n time.localtime(current_time))))\n if current_time > self.__next_report:\n # Print summary and set time of next report\n print('***** Summary *****')\n print('%2u detections for total of %6.2f secconds.'\n % (self.__number_of_rises,\n self.__seconds_at_high))\n self.__number_of_rises = 0\n self.__seconds_at_high = 0.0\n self.__next_report = current_time + REPORT_FREQUENCY\n\n\n\n","repo_name":"inertiaBill/iot-experimentation","sub_path":"button-and-pir/pir.py","file_name":"pir.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16121029649","text":"# Create a line plot showing the number of marriages and divorces per capita in the\n# U.S. between 1867 and 2014. Label both lines and show the legend.\n# Don't forget to label your axes!\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndf = pd.read_csv('us-marriages-divorces-1867-2014.csv')\nprint(df.columns)\nfor i in range(len(df.index)):\n df.at[i, 'Marriages_per_capita'] = float(df.at[i, 'Marriages'])/float(df.at[i, 'Population'])\nfor i in range(len(df.index)):\n df.at[i, 'Divorces_per_capita'] = float(df.at[i, 'Divorces'])/float(df.at[i, 'Population'])\n\nplt.plot(df['Year'], df['Marriages_per_capita'], color='green', marker='.', label='Marriages_per_capita')\nplt.plot(df['Year'], df['Divorces_per_capita'], color='red', marker='.', label='Divorces_per_capita')\nplt.title('number of marriages and divorces per capita in the U.S. between 1867 and 2014', fontsize=14)\nplt.xlabel('Year', fontsize=14)\nplt.ylabel('number of marriages and divorces per capita', fontsize=14)\nplt.grid = True\nplt.legend()\nplt.show()","repo_name":"patelabhi574/Problem-Set-3","sub_path":"question_6.py","file_name":"question_6.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"11581568564","text":"from __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom PIL import Image\nimport matplotlib as plt\n\nimport torchvision.transforms as transforms\nimport torchvision.models as models\n\nimport copy\n\n# GPU checker - will use the GPU if available\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n# helper function to load the image\ndef image_loader(image_name, imsize):\n\n # resizes the image to appropriate size and transforms the image into tensor\n loader = transforms.Compose([transforms.Resize(imsize), transforms.ToTensor()])\n\n image = Image.open(image_name)\n image = loader(image).unsqueeze(0)\n return image.to(device, torch.float)\n\n\n# Shows the image\ndef imshow(tensor, title=None):\n # To reconvert the tensor back to an image at the end\n unloader = transforms.ToPILImage()\n\n # clones the tensor so it doesn't make changes on the original image\n image = tensor.cpu().clone()\n image = image.squeeze(0)\n image = unloader(image)\n plt.imshow(image)\n if title is not None:\n plt.title(title)\n plt.pause(0.0001)\n\n\n# Helper function to find the Style Loss\ndef gram_matrix(input):\n a, b, c, d = input.size()\n# a = batch size\n# b = number of feature maps\n# c, d = dimensions of the feature map N = c*d\n\n features = input.view(a * b, c * d)\n\n# finds the gram product\n G = torch.mm(features, features.t())\n # normalises the gram matrix by dividing by the number of elements in each feature map\n\n return G.div(a * b * c * d)\n\n\n# Content Loss Class\nclass ContentLoss(nn.Module):\n def __init__(self, target):\n # detaches the target content to compute the gradient\n # this is a stated value\n super(ContentLoss, self).__init__()\n self.target = target.detach()\n\n # finds the loss between the input and the target\n def forward(self, input):\n self.loss = F.mse_loss(input, self.target)\n return input\n\n\n# Style Loss\nclass StyleLoss(nn.Module):\n\n def __init__(self, target_feature):\n super(StyleLoss, self).__init__()\n self.target = gram_matrix(target_feature).detach()\n\n def forward(self, input):\n G = gram_matrix(input)\n self.loss = F.mse_loss(G, self.target)\n return input\n\n\n# Helper class for the vgg network\n# Create a module to normalise input image, ready to be put in sequential module\nclass Normalization(nn.Module):\n\n def __init__(self, mean, std):\n super(Normalization, self).__init__()\n\n # view the mean and std to work directly with the tensor image shape\n self.mean = torch.tensor(mean).view(-1, 1, 1)\n self.std = torch.tensor(std).view(-1, 1, 1)\n\n def forward(self, img):\n # normalise img\n return (img - self.mean) / self.std\n\n\n\n# Special values for the mean and standard deviation provided by the research paper\ncnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)\ncnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)\n\n\n# layers to compute style/content losses\ncontent_layers_default = ['conv_4']\nstyle_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']\n\n\ndef get_style_model_and_losses(cnn, normalization_mean, normalization_std,\n style_img, content_img,\n content_layers=content_layers_default,\n style_layers=style_layers_default):\n cnn = copy.deepcopy(cnn)\n\n normalization = Normalization(normalization_mean, normalization_std).to(device)\n\n # list for iteratable access\n content_losses = []\n style_losses = []\n\n # creates a new sequential network for modules that are activated sequentially\n model = nn.Sequential(normalization)\n\n i = 0 # counter for the conv\n for layer in cnn.children():\n if isinstance(layer, nn.Conv2d):\n i += 1\n name = 'conv {}'.format(i)\n elif isinstance(layer, nn.ReLU):\n name = 'relu{}'.format(i)\n\n layer = nn.ReLU(inplace=False)\n elif isinstance(layer, nn.MaxPool2d):\n name = 'pool{}'.format(i)\n elif isinstance(layer, nn.BatchNorm2d):\n name = 'bn{}'.format(i)\n else:\n raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))\n\n model.add_module(name, layer)\n\n if name in content_layers:\n # adds content loss\n target = model(content_img).detach()\n content_loss = ContentLoss(target)\n model.add_module(\"content_loss_{}\".format(i), content_loss)\n content_losses.append(content_loss)\n\n if name in style_layers:\n # adds style loss\n target = model(style_img).detach()\n style_loss = StyleLoss(target)\n model.add_module(\"style_loss_{}\".format(i), style_loss)\n style_losses.append(style_loss)\n\n # trims the the layers after the last content and style losses\n for i in range(len(model) - 1, -1, -1):\n if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):\n break\n\n model = model[:(i + 1)]\n\n return model, style_losses, content_losses\n\n\n# Gradient Descent\ndef get_input_optimizer(input_img):\n # shows that the input needs a gradient\n optimizer = optim.LBFGS([input_img.requires_grad()])\n return optimizer\n\n\n# size of image depending if GPU is available or not\nimsize = 512 if torch.cuda.is_available() else 128\n\nnum_steps = 300\n# loading the style and content images\nstyle_img = image_loader()\ncontent_img = image_loader()\n\n# Sets the plotting to be interactive\nplt.ion()\n\nplt.figure()\nimshow(style_img, title='Style Image')\n\nplt.figure()\nimshow(content_img, title='Content Image')\n\n# importing the vgg 19 model and set it in evaluation mode\ncnn = models.vgg19(pretrained=True).features.to(device).eval()\n\n# The starting image and output\ninput_img = content_img.clone()\n# White noise instead uncomment to use\n# input_img = torch.randn(content_img.data.size(), device=device)\n\n# Shows the input image\nplt.figure()\nimshow(input_img, title='Input Image')\n\n\ndef run_style_transfer(model, style_losses, content_losses,\n input_img, num_steps=300,\n style_weight=1000000, content_weight=1):\n\n optimizer = get_input_optimizer(input_img)\n\n print('Optimizing..')\n\n run = [0]\n while run[0] <= num_steps:\n\n def closure():\n # correct the values of the updated input image\n input_img.data.clamp_(0, 1)\n\n optimizer.zero_grad()\n model(input_img)\n style_score = 0\n content_score = 0\n\n for sl in style_losses:\n style_score += sl.loss\n for cl in content_losses:\n content_score += cl.loss\n\n style_score *= style_weight\n content_score *= content_weight\n\n loss = style_score + content_score\n loss.backward()\n\n run[0] += 1\n\n # prints information each 50 epoch\n if run[0] % 50 == 0:\n print(\"run {}:\".format(run))\n print(\"Style loss : {:4f} Content loss: {:4f}\".format(\n style_score.item(), content_score.item()))\n print()\n\n return style_score + content_score\n\n optimizer.step(closure)\n\n input_img.data.clamp_(0, 1)\n\n return input_img\n\n\nprint('Building style transfer model...')\nmodel, style_losses, content_losses = get_style_model_and_losses(cnn, cnn_normalization_mean,\n cnn_normalization_std, style_img, content_img)\n\noutput = run_style_transfer(model, style_losses, content_losses, input_img, num_steps=num_steps)\n\nplt.figure()\nimshow(output, title='Output image')\n\nplt.ioff()\nplt.show()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"kakinglow/Selective-Style-Transfer","sub_path":"Computing Project/Style Transfer.py","file_name":"Style Transfer.py","file_ext":"py","file_size_in_byte":7906,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"42125273091","text":"from flask import Flask, request, redirect, render_template, session, flash\nfrom flask_sqlalchemy import SQLAlchemy\nimport datetime \n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:password@localhost:8889/build-a-blog'\napp.config['SQLALCHEMY_ECHO'] = True\ndb = SQLAlchemy(app)\napp.secret_key = 'iewgbaklsjhd'\n\nclass Blog(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(120))\n body = db.Column(db.String(300))\n date_time = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n\n def __init__(self, title, body):\n self.title = title\n self.body = body\n \n@app.route('/', methods=['GET'])\ndef index():\n blogs = Blog.query.order_by(Blog.date_time.desc()).all()\n return render_template('blog.html', blogs=blogs)\n\n@app.route('/blog', methods=['GET'])\ndef blog():\n blog_id = request.args.get('id')\n if blog_id:\n blog = Blog.query.filter_by(id=blog_id).first()\n return render_template('blog_item.html', blog=blog)\n return redirect('/')\n\n@app.route('/newpost', methods=['GET','POST'])\ndef newpost():\n title_error = ''\n body_error = ''\n\n if request.method == 'POST':\n blog_title = request.form['title']\n blog_body = request.form['body']\n if not blog_title:\n title_error = 'Title cannot be blank'\n if not blog_body:\n body_error = 'Blog cannot be blank'\n if title_error or body_error:\n return render_template('newpost.html', \n old_title=blog_title, old_body=blog_body, \n title_error=title_error, body_error=body_error)\n new_blog = Blog(blog_title, blog_body)\n db.session.add(new_blog)\n db.session.commit()\n return render_template('blog_item.html', blog=new_blog)\n \n return render_template('newpost.html')\n\n\nif __name__ == '__main__':\n app.run()","repo_name":"JamesCook75/build-a-blog","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4844638340","text":"# To run puautogui\n# sudo pip3 install python3-xlib\n# sudo apt-get install scrot\n# sudo apt-get install python3-tk\n# sudo apt-get install python3-dev\n# sudo pip install pyautogui #[If sudo is not added, there will be an error]\n\nimport time\nimport pyautogui\nimport webbrowser\n\n\n# Navigate to server/channel on discord app\ndef navigate_to_server(base_url, server_id, channel_id):\n webbrowser.open(base_url + '/channels/' + server_id + '/' + channel_id)\n time.sleep(10)\n\n\n# Operates the discord members extension\ndef operate_discord_extension():\n extension_button_location = pyautogui.locateOnScreen('/home/hamza/Pictures/discord_extension_icon.png')\n pyautogui.click(extension_button_location)\n time.sleep(3)\n csv_button_location = pyautogui.locateOnScreen('/home/hamza/Pictures/csv_button.png')\n pyautogui.click(csv_button_location)\n\n time.sleep(2)\n\n csv_button_location = pyautogui.locateOnScreen('/home/hamza/Pictures/go.png')\n pyautogui.click(csv_button_location)\n\n\nif __name__ == '__main__':\n # pre-requisites required\n base_url = \"https://discord.com\"\n server_id = \"722272427354357771\"\n channel_id = \"722273070995210360\"\n\n navigate_to_server(base_url, server_id, channel_id)\n operate_discord_extension()\n","repo_name":"MHA10/Selenium-PyAutoGUI-Discord-Automation","sub_path":"pyautogui_discord_members.py","file_name":"pyautogui_discord_members.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"70084643799","text":"'''\n@Author: your name\n@Date: 2020-06-09 18:11:07\n@LastEditTime: 2020-06-09 18:11:08\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: /Cracking_the_Code_Interview/Leetcode/String/205.Isomorphic_Strings.py\n'''\n# Given two strings s and t, determine if they are isomorphic.\n\n# Two strings are isomorphic if the characters in s can be replaced to get t.\n\n# All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.\n\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n if len(set(s)) == len(set(t)):\n m = {}\n for i in range(len(s)):\n if s[i] not in m:\n m[s[i]] = t[i]\n else:\n if t[i] != m[s[i]]:\n return False\n return True\n return False","repo_name":"lzxyzq/Cracking_the_Coding_Interview","sub_path":"Cracking_the_Code_Interview/Leetcode/3.String/205.Isomorphic_Strings.py","file_name":"205.Isomorphic_Strings.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"23362926518","text":"# Based on https://github.com/awjuliani/DeepRL-Agents/blob/master/Vanilla-Policy.ipynb\n# Originally a Policy Gradient algorithm, upgraded to an Actor-Critic algorithm.\n\nimport itertools\n\nimport gym\nimport tensorflow as tf\n\nfrom polyrl.PolicyEstimator import PolicyEstimator\nfrom util import *\n\n\ndef discount_rewards(r):\n \"\"\" take 1D float array of rewards and compute discounted reward \"\"\"\n gamma = 0.99 # The discount rate\n\n discounted_r = np.zeros_like(r)\n running_add = 0\n for t in reversed(range(0, r.size)):\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n\n\ndef reinforce(env, sess, policy_estimator, total_episodes=None, max_timesteps_per_episode=None, summary_writer=None):\n total_reward = []\n for episode_num in range(total_episodes) if total_episodes is not None else itertools.count():\n state = env.reset()\n ep_history = []\n total_episode_reward = 0\n for timestep in range(\n max_timesteps_per_episode) if max_timesteps_per_episode is not None else itertools.count():\n # Get an action from the policy estimator\n action = policy_estimator.predict(state)\n # Take a step in the environment\n next_state, reward, done, _ = env.step(action)\n total_episode_reward += reward\n reward = 5.0 if done else -0.1\n # Save the transition in the replay memory\n ep_history.append([state, action, reward, next_state, done])\n state = next_state\n print('\\rtimestep={}'.format(timestep), end='')\n\n if done:\n break\n\n # Update the network.\n ep_history = np.array(ep_history)\n ep_history[:, 2] = discount_rewards(ep_history[:, 2])\n policy_estimator.update(state=np.vstack(ep_history[:, 0]), action=ep_history[:, 1], td_target=ep_history[:, 2],\n apply_grads=episode_num % 5 == 0 and episode_num != 0)\n # Reward summary\n if summary_writer is not None:\n global_step = sess.run(tf.contrib.framework.get_global_step())\n summary = tf.Summary(value=[tf.Summary.Value(tag='reward', simple_value=total_episode_reward)])\n summary_writer.add_summary(summary, global_step=global_step)\n\n total_reward.append(total_episode_reward)\n # Update our running tally of scores.\n if episode_num % 100 == 0:\n print(\"\\repisode={}\\tglobal_step={}\\tavg_reward={}\".format(episode_num,\n sess.run(tf.contrib.framework.get_global_step()),\n np.mean(total_reward[-100:])))\n\n\nif __name__ == '__main__':\n env = gym.make('Acrobot-v1')\n\n logdir = '/home/wesley/data/polygons_reinforce'\n reset_dir(logdir)\n\n with tf.Session() as sess:\n tf.Variable(0, name=\"global_step\", trainable=False)\n summary_writer = tf.summary.FileWriter(logdir)\n policy_estimator = PolicyEstimator(state_size=env.observation_space.shape, action_size=env.action_space.n,\n tf_session=sess, summary_writer=summary_writer)\n summary_writer.add_graph(sess.graph)\n sess.run(tf.global_variables_initializer())\n\n reinforce(env=env, sess=sess, policy_estimator=policy_estimator, total_episodes=None,\n max_timesteps_per_episode=500)\n","repo_name":"Shadowen/ImageSegmentation","sub_path":"polyrl/MonteCarloPolicyGradient.py","file_name":"MonteCarloPolicyGradient.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"72928810837","text":"#!/Users/im4jc60/.pyenv/shims/python\n\"\"\"\nCOVID-19 webscraper for USA.\n\ncreated by AUcod3r on 9 March 2020\n\nUses the site https://www.worldometers.info/coronavirus/country/us/\nto track infections and dispositions in the USA\n\"\"\"\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport datetime as dt\nimport os\n\n\ndef readData():\n \"\"\"\n Read yesterday's data from the covidData text file.\n\n This code will grab the last line for daily calculations and deltas.\n \"\"\"\n with open('covidData.txt', 'r') as fRead:\n for line in fRead:\n pass\n last = line.split(' ')\n yestCaseNum = int(last[4].replace(',', ''))\n yestRecover = int(last[7].replace(',', ''))\n yestDeaths = int(last[10].replace(',', ''))\n return yestCaseNum, yestRecover, yestDeaths\n\n\ndef calDeltas(yCNum, yRNum, yDNum, todayValues):\n \"\"\"\n Calculate the differences from yesterday's numbers.\n\n This code will print to the terminal and right now, doesn't write to a\n file.\n \"\"\"\n # Initialize an array to hold int data\n intVals = []\n for i in range(len(todayValues)):\n # Convert string values to intergers:\n intVals.append(int(todayValues[i].replace(',', '')))\n # Calculate and print case differences\n caseNumDiff = intVals[0] - yCNum\n if intVals[0] > yCNum:\n print(f'The total number of cases increased by {caseNumDiff}'\n f' since yesterday')\n elif caseNumDiff == 0:\n print('Hallelujah, no additional cases!')\n else:\n print(\n f'Hopefully, we have turned the corner. There are '\n f'{abs(caseNumDiff)} less cases today!')\n # Calculate and print death differences\n caseDeathDiff = intVals[1] - yDNum\n if caseDeathDiff > 1:\n print(f'Unfortunately, {caseDeathDiff} people died yesterday')\n elif caseDeathDiff == 1:\n print(f'Unfortunately, {caseDeathDiff} person died yesterday')\n else:\n print('Hallelujah, no additional deaths!')\n\n caseRecoveredDiff = intVals[2] - yRNum\n if caseRecoveredDiff > 0:\n print(f'{caseRecoveredDiff} people recovered!!!')\n else:\n print('No change in recovered cases...')\n\n\ndef writeData():\n \"\"\"\n Append the data to covidData.txt.\n\n Keeps track of daily activity and deltas.\n \"\"\"\n with open('covidData.txt', 'a') as f:\n f.write(\n f'{today} - Cases today: {values[0]} - Recovered: '\n f'{values[2]} - Deaths: {values[1]}\\n')\n\n\n# Grab the source and keep this assignment under 80 chars\nhtml_source = (requests.get\n ('https://www.worldometers.info/coronavirus/country/us/').text)\n\n# Create the BeautifulSoup object from the source code\nsoup = BeautifulSoup(html_source, 'lxml')\n\ntoday = dt.datetime.today().strftime(\"%m-%d-%Y\")\n\n# Print to the terminal after clearing screen\nos.system('clear')\nprint(\n \"\\n************* United States of America COVID-19 Data ***************\\n\")\nprint(\"Today's date:\", today)\n# Create 2 empty lists to grab the data from the soup object\nlabels = []\nvalues = []\n# Grab the labels and values from the appropriate divs\nfor headline in soup.find_all('div', id='maincounter-wrap'):\n labels.append(headline.h1.text.strip(' \\n'))\n values.append(headline.find(class_='maincounter-number').text.strip(' \\n'))\n# Grab the labels and values from the appropriate divs\n# for cases in soup.find_all('div', class_='col-md-6'):\n# labels.append(cases.find(class_='panel-heading').text.strip(' \\n'))\n# values.append(cases.find(class_='number-table-main').text.strip(' \\n'))\n# Print to the terminal\nfor i in range(len(labels)):\n print(labels[i], values[i])\nprint()\n# Read yeseterday's data\nyCNum, yRNum, yDNum = readData()\n\n# Caluculate and print the deltas\ncalDeltas(yCNum, yRNum, yDNum, values)\n\n# Call the function to write today's data\nwriteData()\n# Print a nice little divider\nprint(\"\\n**************************************\\n\")\n# Print the last 10 days of data to the screen\nos.system(\"tail -n 10 covidData.txt\")\n","repo_name":"AUcod3r/covid19","sub_path":"covid19.py","file_name":"covid19.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"22616408648","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#reading and loading the data\ndef load_data():\n URL_='https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\n data = pd.read_csv(URL_, header = None)\n print(data)\n\n# make the dataset linearly separable\n data = data[:100]\n data[4] = np.where(data.iloc[:, -1]=='Iris-setosa', 0, 1)\n data = np.asmatrix(data, dtype = 'float64')\n return data\n\ndata = load_data()\n\n\n#plotting the scatter graph\nplt.scatter(np.array(data[:50,0]), np.array(data[:50,2]), marker='o', label='setosa')\nplt.scatter(np.array(data[50:,0]), np.array(data[50:,2]), marker='x', label='versicolor')\nplt.xlabel('petal length')\nplt.ylabel('sepal length')\nplt.legend()\nplt.show()\n\n#checking the class based on threshold\ndef step_check(v):\n if v >= 0:\n return 1\n else: \n return 0\n\n \ndef perceptron(data, num_iter, learning_rate, bias):\n \n features = np.array([])\n w = np.array([bias, 1.0, 1.0])\n\n for i in range(data.shape[0]):\n a = data[i, 0]\n b = data[i, 2]\n jar = np.array([a, b])\n features = np.append(features, jar)\n \n features = np.resize(features, (100, 2))\n labels = [0.0] * 50\n for j in range(50):\n labels.append(1.0)\n \n \n \n accuracy_rate = [] \n \n for epoch in range(num_iter):\n errors = 0\n \n for i in range(features.shape[0]):\n v = np.dot(w[1:], features[i]) + w[0]\n y = step_check(v)\n if(y < labels[i]): \n errors += 1\n w[1:] += (learning_rate * features[i])\n w[0] = w[0] + learning_rate\n elif y > labels[i]:\n errors += 1\n w[1:] = w[1:] - learning_rate * features[i]\n w[0] = w[0] - learning_rate\n accuracy_rate.append(100.0 - errors)\n return (w, accuracy_rate)\n \nnum_iter = 1000\n\nw, accuracy_rate = perceptron(data, num_iter, 0.0001, 0.5)\n#plotting the graph\nepochs = np.arange(1, num_iter+1)\nplt.plot(epochs, accuracy_rate, linestyle = 'dashed', label = \"class 0 and 1\")\nplt.xlabel('Iterations')\nplt.ylabel('Accuracy %age')\nplt.xlim([0, 200])\nplt.legend()\nplt.show()\n\n#scatter plot\nplt.scatter(np.array(data[:50,0]), np.array(data[:50,2]), marker='o', label='setosa')\nplt.scatter(np.array(data[50:,0]), np.array(data[50:,2]), marker='x', label='versicolor')\nplt.xlabel('petal length')\nplt.ylabel('sepal length')\nplt.xlim([3, 8])\nplt.ylim([0, 7])\nx = np.linspace(-5, 10, 500)\ny = (-w[0] - w[1]*x) / w[2]\nplt.plot(x, y, color = \"red\", label = \"class 0 and 1\")\nplt.legend()\nplt.show()","repo_name":"neeraj2681/Neural-Network-Models","sub_path":"Perceptron-Model-for-binary-classification-from-Scratch-master/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20493436271","text":"\n# coding=utf-8\nfrom glPdf.glReportAsPDF import GLReportAsPDF\nfrom reportlab.platypus.paragraph import Paragraph\nfrom reportlab.platypus import PageBreak\nimport datetime\nimport logging\nimport calendar\nimport time\nfrom django.db import connection\n\nfrom pumpsModule.models import GLStation\nfrom pumpsModule.models import GLCustomer\nfrom pumpsModule.models import GLUser\nfrom pumpsModule.models import GLShift\nfrom pumpsModule.models import GLPartialDelivery\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import SimpleDocTemplate, Table, TableStyle\n\n\nlogger = logging.getLogger(__name__)\n\nclass VoissReportDispatcher(GLReportAsPDF):\n\n def __init__(self, filename, **kw):#{{{#\n GLReportAsPDF.__init__(self,filename)\n #}}}#\n\n\n def generateReport(self,request):#{{{#\n\n def addPageNumber(canvas, doc):\n \"\"\"\n Add the page number\n \"\"\"\n page_num = canvas.getPageNumber()\n text = \"Page #%s\" % page_num\n canvas.drawRightString(200*mm, 20*mm, text)\n\n try:\n userId = GLUser.objects.get(vUserId= request.GET['userId'])\n currentShift = GLShift.objects.get(vShift=request.GET['shift'])\n currentStation = GLStation.objects.get(vStationDesc= request.GET['currentStation'])\n if request.GET.get('shift') is None:\n logger.error('shift not found in request, please check the client selection')\n return \n\n if \"null\" in request.GET.get('userId'):\n logger.error('userId not found in request, please check the client selection')\n return \n\n self.header=[]\n\n self.header.append(Paragraph(''+ self.rightSpaces('Reporte Entregas Islas',127)+' ' + str(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S %p')) + '' , self.h2))\n self.header.append(Paragraph(''+self.rightSpaces('Estacion : ',16) +'' + str(currentStation.vStationDesc) +'' , self.h2))\n self.header.append(Paragraph(''+self.rightSpaces('Turno : ',16) +'' + request.GET.get('shift') +'' , self.h2))\n self.header.append(Paragraph(''+self.rightSpaces('Despachador : ',16) + userId.vName + ' ' + userId.vLastname + '' , self.h2))\n self.header.append(Paragraph(' ', self.newline))\n\n self.header.append(Paragraph(' ', self.newline))\n self.header.append(Paragraph(' ', self.newline))\n self.header.append(Paragraph('----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------', self.lineblack))\n\n self.ticketContent.append(Paragraph('----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------', self.lineblack))\n\n \n allDeliveries = GLPartialDelivery.objects.filter(vShiftId=currentShift, vUserId=userId).order_by(\"vPartialDeliveryId\")\n\n elements = []\n data = []\n currentIndex=0\n data.append([])\n data[currentIndex].append(self.rightSpacesTable('Isla',4))\n data[currentIndex].append(self.rightSpacesTable('Fecha',22))\n data[currentIndex].append(self.rightSpacesTable('Total Efectivo',14))\n data[currentIndex].append(self.rightSpacesTable('Total Crédito',14))\n data[currentIndex].append(self.rightSpacesTable('Total Débito',14))\n data[currentIndex].append(self.rightSpacesTable('Total Otros',14))\n data[currentIndex].append(self.rightSpacesTable('Descripción Otros',40))\n data[currentIndex].append(self.rightSpacesTable('Total Final',10))\n\n totalCash=0\n totalCredit=0\n totalDebit=0\n totalOthers=0\n totalFinal=0\n\n for currentDelivery in allDeliveries:\n currentIndex+=1\n data.append([])\n data[currentIndex].append(self.rightSpacesTable(str(currentDelivery.vIsland),4))\n data[currentIndex].append(self.rightSpacesTable(str(currentDelivery.vDate.strftime('%Y/%m/%d %H:%M:%S')),22))\n if currentDelivery.vCashAmount:\n totalCash += float(currentDelivery.vCashAmount)\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(currentDelivery.vCashAmount),14))\n else:\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(\"0\"),14))\n if currentDelivery.vVoucherAmountC:\n totalCredit += float(currentDelivery.vVoucherAmountC)\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(currentDelivery.vVoucherAmountC),14))\n else:\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(\"0\"),14))\n if currentDelivery.vVoucherAmountD:\n totalDebit += float(currentDelivery.vVoucherAmountD)\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(currentDelivery.vVoucherAmountD),14))\n else:\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(\"0\"),14))\n if currentDelivery.vOthersAmount:\n totalOthers += float(currentDelivery.vOthersAmount)\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(currentDelivery.vOthersAmount),14))\n else:\n data[currentIndex].append(self.rightSpacesTable(\"$\"+str(\"0\"),14))\n\n data[currentIndex].append(self.rightSpacesTable(str(currentDelivery.vOthersDesc[:40]),40))\n \n totalFinal=0\n if currentDelivery.vCashAmount:\n totalFinal+= float(currentDelivery.vCashAmount)\n\n if currentDelivery.vVoucherAmountC:\n totalFinal+= float(currentDelivery.vVoucherAmountC)\n\n if currentDelivery.vVoucherAmountD:\n totalFinal+= float(currentDelivery.vVoucherAmountD)\n\n if currentDelivery.vOthersAmount:\n totalFinal+= float(currentDelivery.vOthersAmount)\n\n data[currentIndex].append(self.rightSpacesTable(str(\"$\"+str(totalFinal)),10))\n\n\n currentIndex+=1\n data.append([])\n data[currentIndex].append(self.rightSpacesTable(str(\"\"),4))\n\n\n currentIndex+=1\n data.append([])\n data[currentIndex].append(self.rightSpacesTable(str(\"\"),4))\n data[currentIndex].append(self.rightSpacesTable(str(\"Totales\"),22))\n\n data[currentIndex].append(self.rightSpacesTable(str(\"$\"+str(totalCash)),14))\n data[currentIndex].append(self.rightSpacesTable(str(\"$\"+str(totalCredit)),14))\n data[currentIndex].append(self.rightSpacesTable(str(\"$\"+str(totalDebit)),14))\n data[currentIndex].append(self.rightSpacesTable(str(\"$\"+str(totalOthers)),14))\n data[currentIndex].append(self.rightSpacesTable(str(\"\"),40))\n\n totalFinal= float(totalCash) + float(totalCredit) + float(totalDebit) + float(totalOthers)\n data[currentIndex].append(self.rightSpacesTable(str(\"$\"+str(totalFinal)),10))\n\n\n\n t=Table(data)\n\n t.setStyle(TableStyle([ ('TEXTCOLOR',(0,0),(7,0),colors.blue),\n ('FONTSIZE',(0,0),(7,currentIndex),7),\n ('FONTNAME',(0,0),(7,0),'Times-Bold'),\n ('FONTSIZE',(0,0),(7,0),9)\n ])) \n\n\n elements.append(t)\n self.build(self.header + elements )\n\n except GLStation.DoesNotExist:\n logger.error('Error while trying to get the station : ' + str(request.GET['currentStation']))\n except GLCustomer.DoesNotExist:\n logger.error('Error while trying to get the customerId : ' + str(request.GET['customerId']))\n\n\n #}}}#\n","repo_name":"jSebastianAR/revego","sub_path":"pumps/glPdf/VoissReportDispatcher.py","file_name":"VoissReportDispatcher.py","file_ext":"py","file_size_in_byte":7970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"26826048832","text":"import pandas as pd\nimport numpy as np\nfrom io import StringIO\n# =============================================================================\n# for padding missing values\n# =============================================================================\nfrom sklearn.impute import SimpleImputer\n\ncsv_data = \\\n\"\"\"\nA, B, C, D\n1.0,2.0,3.0,4.0\n5.0,6.0,, 8.0\n10.0,11.0,12.0,\n\"\"\"\n\ndf = pd.read_csv(StringIO(csv_data))\nprint(f\"Raw data:\\n{df}\", '\\n')\n#print(df.isnull(), '\\n')\n#print(df.isnull().sum(), '\\n')\n\n''' Delete missing values '''\ntmp_df = df.dropna(axis=0)\nprint(f\"Delete row(s) if missing:\\n{tmp_df}\", '\\n')\ntmp_df = df.dropna(axis=1)\nprint(f\"Delete column(s) if missing:\\n{tmp_df}\", '\\n')\ntmp_df = df.dropna(how=\"all\")\nprint(f\"Delete column(s) if missing:\\n{tmp_df}\", '\\n')\n\n''' Padding missing values '''\n# method 1:\ncols = df.columns\nimr = SimpleImputer(missing_values=np.nan, strategy=\"mean\")\nimr = imr.fit(df.values)\nimputed_data = pd.DataFrame(imr.transform(df.values), columns=cols)\nprint(f\"Impured data (method 1):\\n{imputed_data}\", '\\n')\n\n# method 2:\ntmp_df = df.fillna(df.mean())\nprint(f\"Impured data (method 2):\\n{tmp_df}\", '\\n')\n","repo_name":"dada00321/ML_practices","sub_path":"practice_04_Data_Preprocessing/recognize_missing_values.py","file_name":"recognize_missing_values.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4889580246","text":"import math\nfrom cv2 import GaussianBlur, imread, log\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nfrom PIL import Image\n\n\ndef main():\n img_path = r'E:\\Digital-image-ProcessingLab\\assignment3\\images\\flower.jpeg'\n img = plt.imread(img_path)\n plt.subplot(3,3,1)\n plt.title('main image')\n plt.imshow(img)\n \n\n #kernels\n kernels = np.ones([3,3])\n print(kernels)\n identityKernel = np.array([[0,0,0],[0,1,0],[0,0,0]])\n ridgeDitectionKernel = np.array([[-1,-1,-1],[-1,16,-1],[-1,-1,-1]])\n ridgeDitectionKernel2 = np.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]])\n sharpenKarnel = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])\n boxBlurKarnel = np.array([[1,1,1],[1,1,1],[1,1,1]])/9\n gaussianBlurKarnel = np.array([[1,2,1],[2,4,2],[1,2,1]])/16\n\n grayscale = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\n plt.subplot(3,3,2)\n plt.title('grayscale image')\n plt.imshow(grayscale,cmap='gray')\n\n identityKernelProcessed = cv2.filter2D(grayscale, -1, identityKernel)\n ridgeDitectionKernelProcessed = cv2.filter2D(grayscale, -1, ridgeDitectionKernel)\n ridgeDitectionKernel2Processed = cv2.filter2D(grayscale, -1, ridgeDitectionKernel2)\n sharpenKarnelProcessed = cv2.filter2D(grayscale, -1, sharpenKarnel)\n boxBlurKarnelProcessed = cv2.filter2D(grayscale, -1, boxBlurKarnel)\n gaussianBlurKarnelProcessed = cv2.filter2D(grayscale,-1,gaussianBlurKarnel)\n\n\n plt.subplot(3,3,3)\n plt.title('identity karnel')\n plt.imshow(identityKernelProcessed,cmap='gray')\n\n plt.subplot(3,3,4)\n plt.title('ridge Ditection karnel')\n plt.imshow(ridgeDitectionKernelProcessed,cmap='gray')\n\n plt.subplot(3,3,5)\n plt.title('Ridge Ditection karnel 2')\n plt.imshow(ridgeDitectionKernel2Processed,cmap='gray')\n\n plt.subplot(3,3,6)\n plt.title('Sharpen Karnel')\n plt.imshow(sharpenKarnelProcessed,cmap='gray')\n\n plt.subplot(3,3,7)\n plt.title('Box Blour Karnel')\n plt.imshow(boxBlurKarnelProcessed,cmap='gray')\n \n plt.subplot(3,3,8)\n plt.title('Gaussian Karnel')\n plt.imshow(gaussianBlurKarnelProcessed,cmap='gray')\n\n plt.show()\n\nmain()","repo_name":"pijushbarai/Digital-image-ProcessingLab","sub_path":"assignment3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"36907679077","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nGiven a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).\n\nFor example:\nGiven binary tree [3,9,20,null,null,15,7],\n 3\n / \\\n 9 20\n / \\\n 15 7\nreturn its zigzag level order traversal as:\n[\n [3],\n [20,9],\n [15,7]\n]\n\"\"\"\n\n__mtime__ = '2018/12/6'\n\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\n# Run 24 ms\nclass Solution(object):\n def zigzagLevelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n\n node_stack = []\n result_list = []\n flag = 0\n\n if root is not None:\n node_stack.append(root)\n\n while len(node_stack) != 0:\n result = []\n new_stack = []\n while len(node_stack) != 0:\n node = node_stack.pop()\n result.append(node.val)\n\n if flag == 0:\n if node.left is not None:\n new_stack.append(node.left)\n if node.right is not None:\n new_stack.append(node.right)\n else:\n if node.right is not None:\n new_stack.append(node.right)\n if node.left is not None:\n new_stack.append(node.left)\n\n result_list.append(result)\n node_stack = new_stack\n flag = 1 - flag\n\n return result_list\n","repo_name":"lee2014/interview_code","sub_path":"leetcode/103_binary_tree_zigzag_level Order Traversal.py","file_name":"103_binary_tree_zigzag_level Order Traversal.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32001339735","text":"text = 'My name is AL SWEIGART and I am 4,000 years old.'\n\nvowels = ('a', 'e', 'i', 'o', 'u', 'y')\n\npigLatina = []\nwords = text.split(' ')\n\nfor word in words:\n prefixNonLetters = ''\n while len(word) > 0 and not word[0].isalpha():\n prefixNonLetters += word[0]\n word = word[1:]\n if len(word) == 0:\n pigLatina.append(prefixNonLetters)\n continue\n\n sufixNonLetters = ''\n while len(word) > 0 and not word[-1].isalpha():\n sufixNonLetters += word[-1]\n word = word[:-1]\n\n wasUpper = word.isupper()\n wasTitle = word.istitle()\n\n word = word.lower()\n\n prefixConsonants = ''\n while len(word)>0 and word[0] not in vowels:\n prefixConsonants += word[0]\n word = word[1:]\n\n if prefixConsonants !='':\n word+=prefixConsonants + 'ay'\n else:\n word+= 'yay'\n\n if wasUpper:\n word = word.upper()\n if wasTitle:\n word = word.title()\n\n pigLatina.append(prefixNonLetters + word + sufixNonLetters)\n\nprint(' '.join(pigLatina))","repo_name":"klimek91/Automate-the-Boring-Stuff-with-Python-SOLUTIONS","sub_path":"Chapter 06 – Manipulating Strings/pig_latin.py","file_name":"pig_latin.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"313570137","text":"#!/usr/bin/env python\n\nimport pyposterous\nfrom logbook import debug, info, warn, error, critical\nimport settings\n\n\ndef post(title, tags='', body='', media=None):\n \"\"\" Upload the given item to Posterous and return the post id.\n \"\"\"\n debug(\"Posting \" + title)\n\n if media:\n media = open(media)\n\n if isinstance(tags, list):\n tags = ','.join(tags)\n\n api = pyposterous.API(username=settings.posterous_username,\n password=settings.posterous_password)\n\n p = api.new_post(site_id=settings.posterous_backup_siteid,\n title=title,\n body=body,\n tags=tags,\n media=media,\n autopost=True)\n\n post_id = str(p.id)\n info(\"Posted \" + title + \" to Posterous. Id = \" + post_id)\n return post_id\n","repo_name":"pombredanne/archiver","sub_path":"posterous.py","file_name":"posterous.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20073301309","text":"from ormik import PkCountError, ModelRegistrationError, fields\n\n__all__ = ['Model']\n\n\nclass ModelMeta(type):\n\n def __new__(mtcls, name, bases, clsdict):\n # Add bases fields to model_cls\n for base_class in bases:\n if not type(base_class) == ModelMeta: continue\n\n for field_name, field in base_class._fields.items():\n clsdict[field_name] = field\n\n # Create model_cls\n model_cls = super().__new__(mtcls, name, bases, clsdict)\n model_cls._fields = {\n attr_name: attr for attr_name, attr in\n model_cls.__dict__.items() if\n isinstance(attr, fields.Field)\n }\n model_cls._table = clsdict.get('__tablename__', name.lower())\n model_cls._pk = None\n\n pk_count = 0\n for model_field_name, model_field in model_cls._fields.items():\n model_field.name = model_field_name\n model_cls._fields[model_field_name] = model_field\n if model_field.is_primary_key:\n if pk_count > 0:\n # PK is already set\n raise PkCountError(\n f'Model \"{model_cls.__name__}\" has >1 PKs.'\n )\n\n model_cls._pk = model_field\n pk_count += 1\n\n # Create reverse_attr for FK model\n if isinstance(model_field, fields.ForeignKeyField):\n setattr(\n model_field.rel_model,\n model_field.reverse_name,\n fields.ReversedForeignKeyField(model_cls, model_field.name)\n )\n\n return model_cls\n\n def __getattr__(cls, attr):\n \"\"\" Make query upon Model class.\n Example: Model.create_table()\n \"\"\"\n qs = cls.query_manager.get_queryset()\n if hasattr(qs, attr):\n def wrapper(*args, **kwargs):\n return getattr(qs, attr)(*args, **kwargs)\n return wrapper\n raise AttributeError(attr)\n\n\nclass Model(metaclass=ModelMeta):\n\n def __init__(self, *args, **kwargs):\n if self._pk is None and self.__class__ is not Model:\n # Model class has no fields\n raise PkCountError(\n f'Model \"{self.__class__.__name__}\" has no PKs.'\n )\n\n if self.query_manager is None:\n # query_manager attribute is set to a model\n # when register in database,\n # e.g. db.register_models(Model)\n raise ModelRegistrationError(\n f'Please, register model '\n f'\"{self.__class__.__name__}\" to database.'\n )\n for field_name, field in self.fields.items():\n field_value = kwargs.get(field_name, field.default_value)\n setattr(self, field_name, field_value)\n\n def __repr__(self):\n fields_repr = ', '.join(\n [\n f'{field_name}={getattr(self, field_name)}'\n for field_name in self.fields.keys()\n ]\n )\n return (\n f'{self.__class__.__name__}({fields_repr}))'\n )\n\n @property\n def fields(self):\n return self.__class__._fields\n\n def save(self, *args, **kwargs):\n saved_inst = self.__class__._save(self, *args, **kwargs)\n self.__dict__ = saved_inst.__dict__\n","repo_name":"Grin941/ormik","sub_path":"ormik/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"25868744988","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 25 16:00:26 2021\r\n\r\n@author: juan m ramírez\r\n\"\"\"\r\n\r\nfrom google.cloud import storage\r\n\r\ndef upload_blob(bucket_name, source_file_name, destination_blob_name):\r\n \"\"\"Uploads a file to the bucket.\"\"\"\r\n bucket_name = \"my-photos\"\r\n source_file_name = \"./puppy.png\"\r\n estination_blob_name = \"puppy01\"\r\n\r\n storage_client = storage.Client()\r\n bucket = storage_client.bucket(bucket_name)\r\n blob = bucket.blob(destination_blob_name)\r\n\r\n blob.upload_from_filename(source_file_name)\r\n\r\n print(\r\n \"File {} uploaded to {}.\".format(\r\n source_file_name, destination_blob_name\r\n )\r\n )\r\n","repo_name":"Juanmanuelramirez/gcp_curso_youtube","sub_path":"storage_python_gcp/storage_up.py","file_name":"storage_up.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"31179719587","text":"#coding:utf-8\nimport numpy as np\nfrom qxlist import df_format\nfrom qxcf import input2numlist\nimport sys\n\ndef nxqx(fileName=\"records_2017-10-16.txt\",recmdIp=\"192.168.216.222\"):\n\t\n\tf = open(fileName)\n\tline = f.readline()\n\trowNumber = 1\n\tinputlist = []\n\tprint(\"读取数据\")\n\twhile line:\n\t\tinputlist.append(line)\n\t\tline = f.readline()\n\t\trowNumber += 1\n\n\tprint(\"读数据完成\")\n\t# print(inputlist)\n\tmainList = []\n\tfor x in xrange(len(inputlist)):\n\t\ttempArray = inputlist[x]\n\t\tsplittedArray = tempArray.split(\",\")\n\t\t# print(splittedArray)\n\t\tmainList.append(splittedArray)\n\n\t\t# print(splittedArray)\n\t\t# mainArray = np.append(mainArray,[splittedArray])\n\n\n\t# print(mainList)\n\tprint(len(mainList))\n\tprint(len(mainList[0]))\n\t# print(mainList[0])\n\titem_id = []\n\tuser_id = []\n\titem_link = []\n\n\tfor x in xrange(len(mainList)):\n\t\tif mainList[x][0].decode(\"utf-8\") == u\"basic\":\n\t\t\t\n\t\t\titem_id.append(mainList[x][2])\n\t\t\tuser_id.append(mainList[x][6])\n\t\t\titem_link.append(mainList[x][3])\n\n\t# print(item_id)\n\t# print(len(item_id))\n\t# print(len(user_id))\n\t# print(len(item_link))\n\trecmdList = input2numlist(item_id,user_id,recmdIp)\n\t# print(recmdList)\n\trecmdLinkList = []\n\tfor x in xrange(len(recmdList)):\n\t\tpos = item_id.index(recmdList[x])\n\t\t# print(pos)\n\t\trecmdLinkList.append(item_link[pos])\n\n\n\t# print(recmdLinkList)\n\treturn recmdList,recmdLinkList\n\nif __name__ == '__main__':\n\tfileName = sys.argv[1]\n\trecmdIp = sys.argv[2]\n\tprint(fileName,recmdIp)\n\trecmdList,recmdLinkList=nxqx()\n\tfwrite = file(\"result.txt\",\"a+\")\n\tfor x in xrange(len(recmdList)):\n\t\ttempStr = str(recmdList[x]) + \",\" +str(recmdLinkList[x]) + \"\\n\"\n\t\tfwrite.write(tempStr)\n\tfwrite.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Inspiring26/wow_public","sub_path":"CollaborativeFiltering/cfnx.py","file_name":"cfnx.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"34454786612","text":"def coloring(incidence):\n if incidence >= 500:\n return \"#d80182\"\n elif incidence > 250:\n return \"#651212\"\n elif incidence > 100:\n return \"#921214\"\n elif incidence > 50:\n return \"#d03523\"\n elif incidence > 5:\n return \"#faee7d\"\n elif incidence > 0:\n return \"#faf7c9\"\n else :\n return \"#ccf5c4\"\n\ncolors = [\n {\"color\": \"#ccf5c4\", \"max\": 0},\n {\"color\": \"#faf7c9\", \"min\": 0, \"max\": 5},\n {\"color\": \"#faee7d\", \"min\": 6, \"max\": 50},\n {\"color\": \"#d03523\", \"min\": 51, \"max\": 100},\n {\"color\": \"#921214\", \"min\": 101, \"max\": 200},\n {\"color\": \"#651212\", \"min\": 201, \"max\": 500},\n {\"color\": \"#faf7c9\", \"min\": 500}\n ]\n","repo_name":"healthIMIS/aha-kompass","sub_path":"api/utils/coloring.py","file_name":"coloring.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"7186773092","text":"# 괄호 - S4\n\nimport sys\n\nn=int(sys.stdin.readline())\n\nstack=[]\ncheck='YES'\nfor _ in range(n):\n bracket=sys.stdin.readline()\n for j in bracket:\n if j=='(':\n stack.append(j)\n elif j==')':\n if '(' in stack:\n stack.remove('(')\n else:\n check='NO'\n\n if len(stack)>0:\n check='NO'\n print(check)\n \n stack=[]\n check='YES'","repo_name":"enriver/algorithm_python","sub_path":"Data Structure/Stack/BOJ_9012.py","file_name":"BOJ_9012.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"69870909718","text":"import collections\n\nimport idc\nimport ida_name\nimport idautils\nimport ida_funcs\nimport ida_hexrays\n\n#-----------------------------------------------------------------------------\n# Scraping Code\n#-----------------------------------------------------------------------------\n\nclass MinsnVisitor(ida_hexrays.minsn_visitor_t):\n \"\"\"\n Hex-Rays Micro-instruction Visitor\n \"\"\"\n found = set()\n\n def visit_minsn(self):\n\n # we only care about external (unsupported) instructions\n if self.curins.opcode != ida_hexrays.m_ext:\n return 0\n \n ins_text = idc.GetDisasm(self.curins.ea)\n ins_op = ins_text.split(\" \")[0]\n\n print(\"- 0x%08X: UNSUPPORTED %s\" % (self.curins.ea, ins_text))\n self.found.add(ins_op)\n return 0\n\ndef scrape_unsupported_instructions():\n \"\"\"\n Scrape all 'external' (unsupported) decompiler instructions from this IDB.\n\n Returns a tuple of two maps:\n ext2func = { opcode: set([func_ea, func2_ea, ...]) }\n func2ext = { func_ea: set([opcode1, opcode2, opcode3]) }\n\n \"\"\"\n miv = MinsnVisitor()\n ext2func = collections.defaultdict(set)\n func2ext = {}\n \n for address in idautils.Functions():\n \n #address = 0x1800017E0 \n print(\"0x%08X: DECOMPILING\" % address)\n func = ida_funcs.get_func(address)\n \n func_mbr = ida_hexrays.mba_ranges_t(func)\n hf = ida_hexrays.hexrays_failure_t()\n flags = ida_hexrays.DECOMP_NO_XREFS | ida_hexrays.DECOMP_NO_WAIT | ida_hexrays.DECOMP_WARNINGS\n mba = ida_hexrays.gen_microcode(func_mbr, hf, None, flags, ida_hexrays.MMAT_GENERATED)\n \n if not mba:\n print(\" - 0x%08x: FAILED %s\" % (hf.errea, hf.str))\n continue\n \n miv.found = set()\n mba.for_all_insns(miv)\n \n # opcode --> [func_ea, func2_ea, ..]\n for ins_op in miv.found:\n ext2func[ins_op].add(address)\n \n # func_ea --> [ins_op, ins_op2, ..]\n func2ext[address] = miv.found\n\n print(\"\\nDone scraping...\\n\")\n return (ext2func, func2ext)\n\ndef print_stats(ext2func):\n \"\"\"\n Print stats about the scraped instructions.\n \"\"\"\n print(\"-\"*60)\n \n func_size_cache = {}\n all_funcs = set()\n \n print(\"\\nFUNC USES -- UNSUPPORTED INSTR (%u types)\\n\" % len(ext2func))\n for key in sorted(ext2func, key=lambda key: len(ext2func[key]), reverse=True):\n function_addresses = ext2func[key]\n all_funcs |= function_addresses\n \n # print the unsupported instruction op, and how many funcs use it\n print(\" - USES: %d - OP: %s\" % (len(function_addresses), key))\n \n # compute the size of all the funcs that use this op..\n func_sizes = []\n for address in function_addresses:\n \n # try to grab the func size if we cached it already\n func_size = func_size_cache.get(address, None)\n if func_size:\n func_sizes.append((func_size, address))\n continue\n \n # compute the size oe the function\n func = ida_funcs.get_func(address)\n func_size = ida_funcs.calc_func_size(func)\n func_sizes.append((func_size, address))\n \n # cache the func size for future use\n func_size_cache[address] = func_size\n \n # print a few small functions that use this unsupported op..\n func_sizes.sort()\n for size, address in func_sizes[:5]:\n print(\" -- SAMPLE FUNC 0x%08X (%u bytes)\" % (address, size))\n\n print(\"\\n\" + \"-\"*60 + \"\\n\")\n print(\"AFFLICTED FUNCTIONS (%u funcs)\\n\" % len(all_funcs))\n \n all_funcs = sorted(all_funcs)\n for ea in all_funcs:\n function_name = ida_name.get_short_name(ea)\n print(\"0x%08X: %s\" % (ea, function_name))\n\n#-----------------------------------------------------------------------------\n# Main\n#-----------------------------------------------------------------------------\n\nprint(\"Scraping instructions...\")\next2func, func2ext = scrape_unsupported_instructions()\nprint(\"Dumping results...\")\nprint_stats(ext2func)\n","repo_name":"gaasedelen/microavx","sub_path":"misc/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","stars":247,"dataset":"github-code","pt":"85"} +{"seq_id":"39366288141","text":"\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n # 二叉搜索树的第K个节点\n res = 0\n def KthNode(self, pRoot, k):\n # write code here\n if not pRoot or k == 0: return\n res = []\n\n def inorder(pRoot):\n if not pRoot or len(res) >= k:\n return\n inorder(pRoot.left)\n res.append(pRoot)\n inorder(pRoot.right)\n\n inorder(pRoot)\n if len(res) < k: return None\n return res[k - 1]\n\n\nclass Solution:\n # 树的子结构\n def HasSubtree(self, pRoot1: TreeNode, pRoot2: TreeNode) -> bool:\n # write code here\n if not pRoot1 or not pRoot2:\n return False\n if self.judge(pRoot1, pRoot2):\n return True\n return self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)\n\n def judge(self, tree, subtree):\n if not subtree: return True\n if not tree: return False\n if tree.val != subtree.val:\n return False\n return self.judge(tree.left, subtree.left) and self.judge(tree.right, subtree.right)\n\nclass Solution:\n # 二叉树的镜像\n def Mirror(self , pRoot ):\n # write code here\n if not pRoot:return\n if not pRoot.left and not pRoot.right:return pRoot\n pRoot.left,pRoot.right=pRoot.right,pRoot.left\n self.Mirror(pRoot.left)\n self.Mirror(pRoot.right)\n return pRoot\n\n\nclass Solution:\n # 二叉搜索树的后续遍历序列\n def VerifySquenceOfBST(self, sequence):\n # write code here\n if not sequence: return False\n root = sequence[-1]\n\n for i in range(len(sequence)):\n if sequence[i] >= root:\n break\n for j in range(i, len(sequence)):\n if sequence[j] < root:\n return False\n\n left = True\n if i > 0:\n left = self.VerifySquenceOfBST(sequence[0:i])\n right = True\n if i < len(sequence) - 1:\n right = self.VerifySquenceOfBST(sequence[i:len(sequence) - 1])\n return left and right\n\nclass Solution:\n # 二叉树中和为某一值的路径\n # 返回二维列表,内部每个列表表示找到的路径\n def FindPath(self, root, expectNumber):\n # write code here\n pathList = []\n res = []\n def PathSum(root,tar):\n if not root:\n return None\n pathList.append(root.val)\n tar -= root.val\n if tar == 0 and not root.left and not root.right:\n res.append(list(pathList))\n PathSum(root.left,tar)\n PathSum(root.right,tar)\n pathList.pop()\n tar += root.val\n PathSum(root,expectNumber)\n return res\n\n\nclass Solution:\n # 二叉搜索树与双向链表\n def Convert(self, pRootOfTree):\n # write code here\n # 中序\n if not pRootOfTree:\n return\n self.head = self.pre = None\n\n def midTraversal(root):\n if not root:\n return\n midTraversal(root.left)\n if not self.head:\n self.head = self.pre = root\n else:\n self.pre.right = root\n root.left = self.pre\n self.pre = root\n midTraversal(root.right)\n\n\nclass Solution:\n # 二叉树的下一个节点\n def GetNext(self, pNode):\n # write code here\n res = []\n cur = pNode\n while cur.next: # 找到根节点\n cur = cur.next\n\n self.inorder(cur, res)\n\n for i in range(len(res)):\n if pNode == res[i]:\n # 判断 i 是不是最后一个结点,是则返回none,否则返回下一个数组结点\n return None if i == len(res) - 1 else res[i + 1]\n return None\n\n # 递归遍历中序\n def inorder(self, cur, res):\n if cur:\n self.inorder(cur.left, res)\n res.append(cur)\n self.inorder(cur.right, res)\n\n\nclass Solution:\n # 1、有右子树,下一结点是右子树中的最左结点\n # 2、无右子树,且结点是该结点父结点的左子树,则下一结点是该结点的父结点\n # 3、无右子树,且结点是该结点父结点的右子树,则一直沿着父结点追朔,直到找到某个结点是其父结点的左子树,如果存在这样的结点,那么这个结点的父结点就是我们要找的下一结点,若并没有符合情况的结点,则没有下一结点\n def GetNext(self, pNode):\n # write code here\n if not pNode:\n return None\n # 有右子树,右子树的最左叶子节点\n if pNode.right:\n res = pNode.right\n while res.left:\n res = res.left\n return res\n # 没有右子树,当前节点是父节点的左子节点\n while pNode.next:\n tmp = pNode.next\n if tmp.left == pNode: # 该节点是父节点的左子树\n return tmp\n # 该节点是父节点的右子树,沿着父节点追溯,直到找到某个结点父节点的左子树\n pNode = pNode.next\n return None # 若没有,则不存在\n\n\nclass Solution:\n # 平衡���叉树\n def IsBalanced_Solution(self, pRoot):\n if not pRoot: return True\n return self.dfs(pRoot) != -1\n\n def dfs(self, node):\n if not node: return 0\n l = self.dfs(node.left)\n if l == -1: return -1 # 若是-1,提前返回,剪枝\n r = self.dfs(node.right)\n if r == -1: return -1\n if abs(l - r) > 1:\n return -1\n return max(l, r) + 1\n\n\nclass Solution:\n # 把二叉树打印成多行\n # 返回二维列表[[1,2],[4,5]]\n def Print(self, pRoot):\n # write code here\n if not pRoot: return []\n q = [pRoot]\n res = []\n while q:\n sz = len(q)\n tmp = []\n for i in range(sz):\n node = q.pop(0)\n tmp.append(node.val)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n res.append(tmp)\n\n return res","repo_name":"ddenglina/Projects","sub_path":"daydayup/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18548967080","text":"import unittest\n\nfrom rdkit import Chem\n\n\nclass TestCase(unittest.TestCase):\n\n def setUp(self):\n #print '\\n%s: '%self.shortDescription(),\n self.m = Chem.MolFromSmiles('CCCC1=CC=C1')\n\n def test1Get(self):\n \" testing GetBond \"\n ok = 1\n try:\n b = self.m.GetBondBetweenAtoms(0, 1)\n except Exception:\n ok = 0\n assert ok, 'GetBond failed'\n\n def test2Setters(self):\n \" testing setting bond props \"\n b = self.m.GetBondBetweenAtoms(0, 1)\n assert b.GetBondType() == Chem.BondType.SINGLE\n b.SetBondDir(Chem.BondDir.BEGINWEDGE)\n assert self.m.GetBondBetweenAtoms(0, 1).GetBondDir() == Chem.BondDir.BEGINWEDGE\n b = self.m.GetBondBetweenAtoms(0, 1)\n\n def test3Props(self):\n \" testing bond props \"\n b = self.m.GetBondBetweenAtoms(0, 1)\n assert b.GetBondType() == Chem.BondType.SINGLE\n assert b.GetBeginAtom().GetIdx() == self.m.GetAtomWithIdx(0).GetIdx()\n assert b.GetBeginAtomIdx() == 0\n assert b.GetEndAtom().GetIdx() == self.m.GetAtomWithIdx(1).GetIdx()\n assert b.GetEndAtomIdx() == 1\n\n def test4Props2(self):\n \" testing more bond props \"\n b = self.m.GetBondBetweenAtoms(3, 4)\n assert b.GetBondType() == Chem.BondType.DOUBLE\n b2 = self.m.GetBondBetweenAtoms(1, 2)\n assert b2.GetBondType() == Chem.BondType.SINGLE\n assert b.GetIsConjugated()\n assert not b2.GetIsConjugated()\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rdkit/rdkit","sub_path":"rdkit/Chem/UnitTestChemBond.py","file_name":"UnitTestChemBond.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":2250,"dataset":"github-code","pt":"85"} +{"seq_id":"14386036136","text":"from _00_configuration._00_settings import *\nfrom _00_configuration._01_variables import *\nfrom _01_functions._00_helper_functions import *\n\n#--------------------------------\n# MASKING\n#--------------------------------\n\ndef mask_veh(df,veh):\n if not isinstance(veh,list):\n mask = (df.vehID == str(veh))\n return df[mask]\n else:\n #mask = (df.vehID in veh)\n return df[df['vehID'].isin(veh)]\n\ndef mask_timestep(df,timestep,columnname = \"time\"):\n if not isinstance(timestep,list):\n mask = (df[columnname] == str(timestep))\n return df[mask]\n else:\n #mask = (df.vehID in veh)\n return df[df[columnname].isin(timestep)]\n\n\n#--------------------------------\n# CLEANING/FORMATTING DF\n#--------------------------------\n\ndef change_columns_names(df,column_names = None):\n if column_names is None:\n columns_names = {'id':'vehID', \n 'x':'X', \n 'y':'Y', \n 'angle':'yaw', \n 'type':'type', \n 'speed':'speed', \n 'pos':'pos', #? \n 'lane':'lane', \n 'slope':'slope',\n #'signals':'signals', # traffic lights? \n }\n df.rename(columns = columns_names, inplace = True)\n return df\n \ndef change_columns_format_to_numeric(df,columns_numeric = None):\n if columns_numeric is None:\n columns_numeric = [\n #'timestep',\n #'vehID',\n 'X','Y', \n 'yaw','pos', \n #'lane', # this one has letters too\n 'speed',\n 'slope',\n #'signals'\n ]\n df[columns_numeric] = df[columns_numeric].apply(pd.to_numeric)\n return df\n\ndef change_vehicles_names(df, column_name = \"vehID\"):\n #df[column_name]= df[column_name].map(lambda x: x.lstrip('flow1.'))\n df[column_name]= df[column_name].map(lambda x: x[6:])\n return df\n\ndef format_df (df, column_names = None, columns_numeric = None, source = \".xml\", shift_coordinates = (0,0)):\n \"\"\"\n custom df formatting \n \"\"\"\n if source == \".xml\":\n df = change_columns_names(df,column_names)\n df = change_vehicles_names(df, column_name = \"vehID\")\n df = change_columns_format_to_numeric(df,columns_numeric)\n \n elif source.isin([\".zip\",\".csv\"]):\n assert 'position (X,Y)' in df.columns\n X,Y = [],[]\n for e in list(map(eval,df['position (X,Y)'])): \n X.append(e[0]+shift_coordinates[0])\n Y.append(e[1]+shift_coordinates[1])\n df.insert(2, 'Y', Y)\n df.insert(2, 'X', X)\n df.drop(columns=['position (X,Y)'] ,inplace = True)\n \n else:\n print (\"accepting only xml,zip and csv files\")\n \n return df\n\n\n#--------------------------------\n# PLOTTING \n#--------------------------------\n\ndef plot_2D(df,palette = \"Paired\" , \n legend = \"True\", \n grid = \"True\",\n figsize=(30,30),\n linewidth=7.0):\n \"\"\"\n visualization of paths\n \"\"\"\n unique_veh = df.vehID.unique().tolist()\n l = len(unique_veh)\n print (f\"{l} unique vehicles found in the simulation\")\n if l < 10: \n print (*unique_veh, sep = \"\\n\")\n cmap = list(sns.color_palette(palette,len(unique_veh)).as_hex())\n fig, ax = plt.subplots(figsize= figsize)\n ax.set_title(\"2D map\");\n ax.set_xlabel(\"X\");\n ax.set_ylabel(\"Y\");\n for i,veh in enumerate(unique_veh):\n df_veh = mask_veh(df,veh)\n if \"X\" in df_veh.columns:\n X = df_veh.X.tolist()\n Y = df_veh.Y.tolist()\n #ax.plot(X,Y,cmap[i], label = str(veh) ,linewidth=linewidth)\n else: \n pos_veh = list(map(eval, df_veh.Position3D))\n X,Y = list(), list()\n for row in pos_veh: \n X.append(row[0])\n Y.append(row[1])\n\n ax.plot(X,Y,cmap[i], label = str(veh) ,linewidth=linewidth)\n if legend:\n ax.legend()\n if grid:\n ax.grid(grid)\n ax.xaxis.grid(True, which='minor')\n\n for i,x in enumerate(X):\n if i% 7 == 0:\n ax.annotate(str(i), (x, Y[i]), ha='center', va='center', size=14)\n\nprint (f\"Functions import successful\")\n\n\n#--------------------------------\n# ADD INTENTION COLUMN\n#--------------------------------\ndef add_intention(df, unique_vehicles):\n for u in unique_vehicles:\n mask_vehID = df['vehID'] == u\n df_vehicle = df[mask_vehID]\n max_timestemp = df_vehicle['time'].max()\n min_timestemp = df_vehicle['time'].min()\n \n maxTime_X = df_vehicle.loc[df_vehicle['time'] == max_timestemp, 'X'].item()\n maxTime_Y = df_vehicle.loc[df_vehicle['time'] == max_timestemp, 'Y'].item()\n \n minTime_X = df_vehicle.loc[df_vehicle['time'] == min_timestemp, 'X'].item()\n minTime_Y = df_vehicle.loc[df_vehicle['time'] == min_timestemp, 'Y'].item()\n \n #zero center - can be probably deleted\n maxTime_X = maxTime_X - 100\n maxTime_Y = maxTime_Y - 100\n minTime_X = minTime_X - 100\n minTime_Y = minTime_Y - 100\n \n ## u-turn get the value 0, straight the value 1, left the value 2 and right the value 3\n # Case one (lower left corner)\n if minTime_X<0 and minTime_Y<0: #1\n if maxTime_X<0 and maxTime_Y>0: #U turn 0\n df.loc[df['vehID'] == u, 'intention'] = 0\n \n elif maxTime_X>0 and maxTime_Y<0: #Straight 1\n df.loc[df['vehID'] == u, 'intention'] = 1\n \n elif maxTime_X>0 and maxTime_Y>0: #Left 2\n df.loc[df['vehID'] == u, 'intention'] = 2\n \n elif maxTime_X<0 and maxTime_Y<0: #Right 3\n df.loc[df['vehID'] == u, 'intention'] = 3\n \n # Case two (lower right corner)\n elif minTime_X>0 and minTime_Y<0: #2\n if maxTime_X<0 and maxTime_Y<0: #U turn 0\n df.loc[df['vehID'] == u, 'intention'] = 0\n \n elif maxTime_X>0 and maxTime_Y>0: #Straight 1\n df.loc[df['vehID'] == u, 'intention'] = 1\n \n elif maxTime_X<0 and maxTime_Y>0: #Left 2\n df.loc[df['vehID'] == u, 'intention'] = 2\n \n elif maxTime_X>0 and maxTime_Y<0: #Right 3\n df.loc[df['vehID'] == u, 'intention'] = 3 \n \n # Case three (upper right corner)\n elif minTime_X>0 and minTime_Y>0: #3\n if maxTime_X>0 and maxTime_Y<0: #U turn 0\n df.loc[df['vehID'] == u, 'intention'] = 0\n \n elif maxTime_X<0 and maxTime_Y>0: #Straight 1\n df.loc[df['vehID'] == u, 'intention'] = 1\n \n elif maxTime_X<0 and maxTime_Y<0: #Left 2\n df.loc[df['vehID'] == u, 'intention'] = 2\n \n elif maxTime_X>0 and maxTime_Y>0: #Right 3\n df.loc[df['vehID'] == u, 'intention'] = 3 \n \n # Case four (upper left corner)\n elif minTime_X<0 and minTime_Y>0: #4\n if maxTime_X>0 and maxTime_Y>0: #U turn 0\n df.loc[df['vehID'] == u, 'intention'] = 0\n \n elif maxTime_X<0 and maxTime_Y<0: #Straight 1\n df.loc[df['vehID'] == u, 'intention'] = 1\n \n elif maxTime_X>0 and maxTime_Y<0: #Left 2\n df.loc[df['vehID'] == u, 'intention'] = 2\n \n elif maxTime_X<0 and maxTime_Y>0: #Right 3\n df.loc[df['vehID'] == u, 'intention'] = 3 \n\n return df \n","repo_name":"arita89/multiagent_system","sub_path":"005_src/_00_configuration/Old_scripts/_03_functions_dataframes.py","file_name":"_03_functions_dataframes.py","file_ext":"py","file_size_in_byte":7726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42806773834","text":"# -*- coding: utf-8 -*-\n\"\"\"\n가사 검색 : https://programmers.co.kr/learn/courses/30/lessons/60060?language=python3\n\"\"\"\n\n\nclass Node:\n def __init__(self, value):\n self.value = value\n self.children = dict()\n self.childrenCount = 0\n\n def hasChildCharacter(self, c):\n if c in self.children:\n return True\n else:\n return False\n\n def getChildNode(self, c):\n if self.hasChildCharacter(c):\n return self.children[c]\n else:\n return None\n\n def getChildren(self):\n return list(self.children.values())\n\n def setChildNode(self, c):\n self.children[c] = Node(c)\n\n def __str__(self, level=0):\n temp = '\\t' * level + f'value: {self.value}, childrenCount = {self.childrenCount}' + '\\n'\n for child in self.children.values():\n temp += child.__str__(level + 1)\n return temp\n\n\ndictionary = dict() # 정방향 사전\ndictionary2 = dict() # 역방향 사전\n\n\ndef makeTree(w, width):\n dictionary.setdefault(width, Node(''))\n curr = dictionary.get(width)\n for c in w:\n curr.childrenCount += 1\n if not curr.hasChildCharacter(c):\n curr.setChildNode(c)\n curr = curr.getChildNode(c)\n\ndef makeReverseTree(w, width):\n dictionary2.setdefault(width, Node(''))\n curr = dictionary2.get(width)\n index = len(w)\n for i in range(index - 1, -1, -1):\n curr.childrenCount += 1\n if not curr.hasChildCharacter(w[i]):\n curr.setChildNode(w[i])\n curr = curr.getChildNode(w[i])\n\ndef search(query):\n width = len(query)\n if query[0] == '?':\n return searchBackward(query, width)\n else:\n return searchForward(query, width)\n\ndef searchForward(query, width):\n answer = 0\n if width not in dictionary:\n return 0\n curr = dictionary.get(width)\n for i in range(width):\n if query[i] == '?':\n answer = curr.childrenCount\n break\n if curr.hasChildCharacter(query[i]):\n curr = curr.getChildNode(query[i])\n else:\n break\n\n return answer\n\n\ndef searchBackward(query, width):\n answer = 0\n if width not in dictionary2:\n return 0\n curr = dictionary2.get(width)\n for i in range(width - 1, -1, -1):\n if query[i] == '?':\n answer = curr.childrenCount\n break\n if curr.hasChildCharacter(query[i]):\n curr = curr.getChildNode(query[i])\n else:\n break\n\n return answer\n\n\ndef solution(words, queries):\n global dictionary, dictionary2\n dictionary = dict()\n dictionary2 = dict()\n answer = []\n\n for word in words:\n makeTree(word, len(word))\n makeReverseTree(word, len(word))\n\n # print(f'dictionary = {repr(dictionary)}')\n # print(f'dictionary2[2] = {repr(dictionary2[2])}')\n # print(searchForward('fro??'))\n # print(searchBackward('????o'))\n for query in queries:\n answer.append(search(query))\n\n return answer\n\n\nif __name__ == '__main__':\n # result = solution([\"frodo\", \"front\", \"frost\", \"frozen\", \"frame\", \"kakao\"], [\"fro??\", \"????o\", \"fr???\", \"fro???\", \"pro?\"])\n # print(f'result = {result}')\n # assert result == [3, 2, 4, 1, 0]\n #\n # result = solution([\"frodo\", \"front\", \"frost\", \"frozen\", \"frame\", \"kakao\"], [\"?????\", \"??????\"])\n # print(f'result = {result}')\n # assert result == [5, 1]\n\n result = solution([\"AB\", \"AC\"], [\"??\", \"A?\", \"?B\"])\n print(f'result = {result}')\n assert result == [2, 2, 1]","repo_name":"junjongwook/programmers","sub_path":"Skill Check/Level4/s60060.py","file_name":"s60060.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18885252126","text":"# -*- coding: utf-8 -*-\nfrom ....models.helpers.date_helpers import format_date_to_day_month_and_year\nfrom ....models.sources import LondonGazette, NewZealandArchives, NominalRoll\nfrom ....models.helpers.sources_helpers import (\n map_nz_archives,\n get_awmm,\n get_nominal_roll,\n map_london_gazette,\n)\n\n\nactual_nz_archives_1 = NewZealandArchives(\"AABK 18805 W5520 1/0006561\", \"22280535\")\nactual_nz_archives_2 = NewZealandArchives(\"AABK 18805 W5520 1/0006563\", \"22280537\")\n\n\nexpected_ref_1 = NewZealandArchives(\n \"AABK 18805 W5520 1/0006561\",\n \"https://collections.archives.govt.nz/web/arena/search#/item/aims-archive/R22280535\",\n)\nexpected_ref_2 = NewZealandArchives(\n \"AABK 18805 W5520 1/0006563\",\n \"https://collections.archives.govt.nz/web/arena/search#/item/aims-archive/R22280537\",\n)\n\n\nclass TestMapNzArchives:\n class TestMapNzArchivesIf:\n def test_map_nz_archives_if_archives_has_one_record(self):\n assert map_nz_archives([actual_nz_archives_1]) == [expected_ref_1]\n\n def test_map_nz_archives_if_archives_has_two_records(self):\n assert map_nz_archives([actual_nz_archives_1, actual_nz_archives_2]) == [\n expected_ref_1,\n expected_ref_2,\n ]\n\n\nclass TestDoNotMapNzArchivesIf:\n def test_do_not_map_nz_archives_if_archives_has_no_record(self):\n assert map_nz_archives([]) == []\n\n\nclass TestGetAwmm:\n def test_get_awmm(self):\n assert (\n get_awmm(\"fake_reference\")\n == \"https://www.aucklandmuseum.com/war-memorial/online-cenotaph/record/fake_reference\"\n )\n\n\nvolume = \"III\"\nroll = \"75\"\npage = \"3\"\n\nen = \"en\"\nfr = \"fr\"\n\nno_break_space = \"\\N{NO-BREAK SPACE}\"\nroll_number_col = {\"en\": \"Roll No.\", \"fr\": \"Liste n\\N{DEGREE SIGN}\"}\n\ntitle_1919 = {\n \"en\": \"Nominal Rolls of New Zealand Expeditionary Force\",\n \"fr\": \"Liste nominative du corps expéditionnaire néo-zélandais\",\n}\ntitle_1916 = {\n \"en\": \"Nominal Roll of New Zealand Expeditionary Force, 1915. New Zealand Engineers Tunnelling Company\",\n \"fr\": \"Liste nominative du corps expéditionnaire néo-zélandais, 1915. Compagnie de tunneliers\",\n}\n\n\nclass TestGetNominalRoll:\n def test_if_volume_and_roll_are_not_none_and_lang_is_en(self):\n assert get_nominal_roll(volume, roll, page, en) == NominalRoll(\n title_1919[en],\n \"Wellington\",\n \"Government Printer\",\n \"1914-1919\",\n \"p.{}{}\".format(no_break_space, page),\n \"Volume{}{}\".format(no_break_space, volume),\n \"{}{}\".format(roll_number_col[en], roll),\n )\n\n def test_if_volume_and_roll_are_not_none_and_lang_is_fr(self):\n assert get_nominal_roll(volume, roll, page, fr) == NominalRoll(\n title_1919[fr],\n \"Wellington\",\n \"Government Printer\",\n \"1914-1919\",\n \"p.{}{}\".format(no_break_space, page),\n \"Volume{}{}\".format(no_break_space, volume),\n \"{}{}\".format(roll_number_col[fr], roll),\n )\n\n def test_if_volume_and_roll_are_none_and_lang_en(self):\n assert get_nominal_roll(None, None, page, en) == NominalRoll(\n title_1916[en],\n \"Wellington\",\n \"Government Printer\",\n \"1916\",\n \"p.{}{}\".format(no_break_space, page),\n )\n\n def test_if_volume_and_roll_are_none_and_lang_fr(self):\n assert get_nominal_roll(None, None, page, fr) == NominalRoll(\n title_1916[fr],\n \"Wellington\",\n \"Government Printer\",\n \"1916\",\n \"p.{}{}\".format(no_break_space, page),\n )\n\n\nlondon_gazette_list = [\n LondonGazette(\"13575\", \"1917-12-28\"),\n LondonGazette(\"29\", \"1918-01-01\"),\n]\n\n\nclass TestMapLondonGazette:\n class TestMapLondonGazetteIf:\n def test_london_gazette_is_not_none_and_lang_is_en(self):\n assert map_london_gazette(london_gazette_list, \"en\") == [\n LondonGazette(\n \"13575\", format_date_to_day_month_and_year(\"1917-12-28\", \"en\")\n ),\n LondonGazette(\n \"29\", format_date_to_day_month_and_year(\"1918-01-01\", \"en\")\n ),\n ]\n\n def test_london_gazette_is_not_none_and_lang_is_fr(self):\n assert map_london_gazette(london_gazette_list, \"fr\") == [\n LondonGazette(\n \"13575\", format_date_to_day_month_and_year(\"1917-12-28\", \"fr\")\n ),\n LondonGazette(\n \"29\", format_date_to_day_month_and_year(\"1918-01-01\", \"fr\")\n ),\n ]\n\n class TestDoNotMapLondonGazetteIf:\n def test_london_gazette_is_none_and_lang_en(self):\n assert map_london_gazette([], \"en\") == []\n\n def test_london_gazette_is_none_and_lang_fr(self):\n assert map_london_gazette([], \"fr\") == []\n","repo_name":"ByAnthony/nztunnellers","sub_path":"server/test/models/helpers/test_sources_helpers.py","file_name":"test_sources_helpers.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"85"} +{"seq_id":"71601085397","text":"import re\nimport os\n\nfrom rest_framework import generics, permissions, status\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework.response import Response\nfrom django.conf import settings\n\nfrom django.http import Http404\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework.decorators import api_view\n\nimport base.utils as utils\nfrom base.models import Resource, Organization\nfrom base.serializers import ResourceSerializer, OrganizationSerializer, TreeObjectSerializer\nfrom analysis.models import AnalysisProjectResource\n\nfrom google.cloud import storage\n\nfrom rest_framework.views import APIView\nfrom django.http import JsonResponse\nclass FileRenameView(APIView):\n\n def post(self, request, *args, **kwargs):\n\n try:\n new_name = request.data['new_name']\n except Exception as ex:\n return JsonResponse({'error': 'Please ensure the payload includes a \"new_name\" key'}, status=400)\n try:\n pk = int(kwargs['pk'])\n except Exception as ex:\n return JsonResponse({'error': 'Please ensure the URL includes an integer primary key'}, status=400)\n\n try:\n r = Resource.objects.get(pk=pk)\n except ObjectDoesNotExist as ex:\n return JsonResponse({'error': 'Resource not found.'}, status=404)\n\n if request.user != r.get_owner():\n return JsonResponse({'error': 'The resource, if it exists, does not belong to the requester.'}, status=404)\n\n # check that the name is relatively normal (only letters, numbers, etc.). Also normalize spaces to be underscores\n new_name = new_name.replace(' ', '_') # first normalize\n m = re.fullmatch('[a-zA-z0-9\\.\\-\\_]*', new_name)\n if m is None:\n return JsonResponse({'error': 'Please ensure your filenames only contain letters, numbers, dashes, underscores, and periods.'}, status=400)\n if len(new_name) < 2:\n return JsonResponse({'error': 'Your filename was too short. Please rename your file using 2 or more characters.'}, status=400)\n\n current_filename = r.name\n current_path = r.path\n current_bucketname = current_path[len(settings.CONFIG_PARAMS['google_storage_gs_prefix']):].split('/')[0]\n new_path = os.path.join( \n os.path.dirname(current_path),\n new_name\n )\n new_object_name = new_path[(len(settings.CONFIG_PARAMS['google_storage_gs_prefix']) + len(current_bucketname))+1:]\n\n #TODO: check that name will be valid on the cloud storage system, regardless\n # of the requirement that the path in the database is unique\n byte_length = len(new_object_name.encode('utf-8'))\n if byte_length >= 1024:\n return JsonResponse({'error': 'The file name was too long. Try again.'}, status=400)\n if byte_length <= 1:\n return JsonResponse({'error': 'The file name was too short. Try again.'}, status=400)\n\n # need to ensure we are not violating uniqueness:\n try:\n conflicting_resource = Resource.objects.get(path=new_path)\n return JsonResponse({'error': 'Our records show that there is already a file with this name. If you would like to overwrite, please delete the other file first.'}, status=400)\n except ObjectDoesNotExist as ex:\n # this means we are OK-- the database did not have such a record-- go ahead and rename\n # need to rename the object in storage:\n \n storage_client = storage.Client()\n try:\n bucket = storage_client.get_bucket(current_bucketname)\n blob = bucket.get_blob(current_path.split('/')[-1])\n bucket.rename_blob(blob, new_name)\n except Exception as ex:\n return JsonResponse({'error': 'Could not perform the rename operation.'}, status=500)\n \n # now we can update the database:\n r.path = new_path\n r.name = new_name\n r.save()\n return JsonResponse({})\n\n\nclass TreeObject(object):\n '''\n This is used to structure data for the front-end when we display files/resources for selection. \n We organize the files by grouping them- they belong to analysis projects, uploads, \n or can be \"unattached\". \n They are displayed by providing a header (title) and some children nodes which are the files to select. \n Each of the children nodes hold information like the file name and the primary key of the resource\n '''\n def __init__(self, title, children):\n '''\n title is the title that would show up in the UI as a \"header\". \n For example, the name of the project that the Resource is associated with\n children is a list of Resource instances\n '''\n self.title = title\n self.children = children\n\n def gui_representation(self):\n '''\n This returns an object that will be passed to the UI. The serializer uses this method\n to construct the serialized data. They keys in this object depend on how we are displaying\n the data on the front-end. \n '''\n d = {}\n d['text'] = self.title\n # below, we use the gui_representation method defined in the Resource class\n d['nodes'] = [x.gui_representation() for x in self.children]\n return d\n\n\n@api_view(['GET'])\ndef get_tree_ready_resources(request):\n '''\n This view gives a tree-ready representation of the data for the front-end.\n '''\n\n # a list of TreeObject instances:\n all_sections = []\n\n user = request.user\n\n # Did the request ask for uploaded objects? If we are showing downloads, we typically would NOT\n # want to show the uploads (why would they download a file they previously uploaded?)\n try:\n include_uploads_str = request.query_params['include_uploads'] # true or false (strings)\n include_uploads = include_uploads_str.lower() == 'true'\n except KeyError:\n include_uploads=False\n\n try:\n regex_filter = request.query_params['regex_filter']\n except KeyError:\n # just in case, if an exception was raised, make this a greedy regex\n regex_filter = '.*'\n\n if include_uploads:\n # We want to denote Resource instances that were created via user uploads to be in their own section:\n uploaded_resources = Resource.objects.user_resources(user).filter(originated_from_upload=True).filter(is_active=True)\n uploaded_resources = [x for x in uploaded_resources if re.fullmatch(regex_filter, x.name)]\n if len(uploaded_resources) > 0:\n upload_section = TreeObject('Uploads', uploaded_resources)\n all_sections.append(upload_section)\n\n # get the non-uploaded resources, if any. These would be Resource instances created as part of an analysis project (or similar)\n all_other_resources = Resource.objects.user_resources(user).filter(originated_from_upload=False).filter(is_active=True)\n\n # get the the subset of non-uploaded Resources that have an association to an AnalysisProject\n analysis_project_resources = AnalysisProjectResource.objects.filter(resource__in = all_other_resources)\n\n # determine the resources that were NOT uploads, but also not associated with projects:\n # typically these files would not exist, but we provide them for potential flexibility in the future\n ap_resource_list = [x.resource for x in analysis_project_resources]\n unassociated_resources = [x for x in all_other_resources if not x in ap_resource_list]\n\n # filter on the names:\n ap_resource_list = [x for x in ap_resource_list if re.fullmatch(regex_filter, x.name)]\n unassociated_resources = [x for x in unassociated_resources if re.fullmatch(regex_filter, x.name)]\n\n if len(unassociated_resources) > 0:\n unassociated_section = TreeObject('Other', unassociated_resources)\n all_sections.append(unassociated_section)\n\n # for the Resource instances associated with analysis projects, we have to display some header/section title \n # in the tree. TODO: change this from the UUID\n d = {}\n for apr in analysis_project_resources:\n project = apr.analysis_project\n wf_title = project.workflow.workflow_title\n try:\n project_date = project.finish_time.strftime('%B %d, %Y (%H:%M:%S)')\n except Exception as ex:\n project_date = '-'\n section_title = '%s (Completed %s)' % (wf_title, project_date)\n if section_title in d:\n d[section_title].append(apr.resource)\n else:\n d[section_title] = [apr.resource,]\n\n for key, resource_list in d.items():\n resource_list = [x for x in resource_list if re.fullmatch(regex_filter, x.name)] \n if len(resource_list) > 0:\n all_sections.append(TreeObject(key, resource_list))\n\n # we now have a list of TreeObject instances. Serialize.\n serializer = TreeObjectSerializer(all_sections, many=True)\n return Response(serializer.data)\n\n\nclass OrganizationList(generics.ListCreateAPIView):\n '''\n This lists or creates the Organizations \n '''\n queryset = Organization.objects.all()\n serializer_class = OrganizationSerializer\n permission_classes = (permissions.IsAdminUser,)\n\n\nclass OrganizationDetail(generics.RetrieveUpdateDestroyAPIView):\n '''\n This is for details, updates, or deletion of a particular instance \n of an Organization\n '''\n queryset = Organization.objects.all()\n serializer_class = OrganizationSerializer\n permission_classes = (permissions.IsAdminUser,)\n\n\nclass ResourceList(generics.ListCreateAPIView):\n '''\n This endpoint allows us to list or create Resources\n See methods below regarding listing logic and creation logic\n Some filtering can be added at some point\n '''\n queryset = Resource.objects.all()\n serializer_class = ResourceSerializer\n permission_classes = (permissions.IsAuthenticated,)\n filter_backends = (DjangoFilterBackend,)\n filter_fields = ('is_active', 'originated_from_upload')\n \n def get_queryset(self):\n '''\n This overrides the get_queryset method of rest_framework.generics.GenericAPIView\n This allows us to return only Resource instances belonging to the user.\n If an admin is requesting, then we return all\n '''\n queryset = super(ResourceList, self).get_queryset()\n if not self.request.user.is_staff:\n queryset = Resource.objects.user_resources(self.request.user)\n return queryset\n\n\n def create(self, request, *args, **kwargs):\n '''\n This override provides us with the ability to create multiple instances\n Pretty much a verbatim copy of the implementation from CreateMixin except\n that we add the many=... kwarg when we call get_serializer\n '''\n serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list))\n utils.create_resource(serializer, self.request.user)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n\nclass ResourceDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Resource.objects.all()\n serializer_class = ResourceSerializer\n permission_classes = (permissions.IsAuthenticated,)\n\n def get_object(self):\n '''\n Custom behavior for object retrieval- admins can get anything\n Regular users can only get objects they own. \n Instead of the default 403 (which exposes that a particular object\n does exist), return 404 if they are not allowed to access an object.\n '''\n obj = super(ResourceDetail, self).get_object()\n if (self.request.user.is_staff) or (obj.get_owner() == self.request.user):\n return obj\n else:\n raise Http404\n\n\nclass UserResourceList(generics.ListAPIView):\n '''\n This lists the Resource instances for a particular user\n This view is entirely protected-- only accessible by staff\n Since regular users can only see the Resources they own,\n they can just use the \"vanilla\" listing endpoint\n '''\n serializer_class = ResourceSerializer\n permission_classes = (permissions.IsAdminUser,)\n filter_backends = (DjangoFilterBackend,)\n filter_fields = ('is_active',)\n\n def get_queryset(self):\n user_pk = self.kwargs['user_pk']\n try:\n user = get_user_model().objects.get(pk=user_pk)\n return Resource.objects.user_resources(user)\n except ObjectDoesNotExist as ex:\n raise Http404\n","repo_name":"qbrc-cnap/cnap","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"70694760278","text":"import multiprocessing as mp\nimport time\n\ndef exponent(x):\n\ttime.sleep(1)\n\treturn x*x\n\ndef main():\n\tnaturalNumbers = [x for x in range(1,10)]\n\tresults = []\n\t\n\tpool = mp.Pool(mp.cpu_count())\n\tstart = time.time()\n\tresults = pool.map(exponent, naturalNumbers)\n\tend = time.time()\n\tpool.close() \n\tduration = end - start\n\n\tprint(\"Parallel using Map: \", results[:10],int(1000*duration),\"ms\")\nif __name__ == '__main__':\n\tmain()\n\tinput() ","repo_name":"blaq/Coursework","sub_path":"CS474 Concurrent Systems/showMap.py","file_name":"showMap.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"20333725592","text":"import pandas as pd\nimport json\n\nfilename = (\"D:\\other\\Excel2Json\\System_Start_Stop_TC1_2.csv\")\noutput = open('temp.json', 'w')\n\nrecords = pd.DataFrame(pd.read_csv(filename)).to_dict('records')\ndict = {}\n\nfor i in range(len(records)):\n dict[\"TestCase\"+str(i+1)] = {\"Data\" : records[i]}\n\noutput.write(json.dumps(dict, sort_keys=True, indent=2, separators=(',', \": \")))\noutput.close()","repo_name":"DevendraPhaniKumar/TestCarrier","sub_path":"STAF/Lib_space/Excel2Json/csv2json_pandas.py","file_name":"csv2json_pandas.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"7324831791","text":"from .config import get_config, finalise\nfrom .train import Trainer\n\n\ndef run(experiment_file_name: str):\n cfg = get_config()\n cfg.merge_from_file(experiment_file_name)\n finalise(cfg)\n\n if cfg.action == 'train':\n trainer = Trainer.from_config(cfg)\n trainer.train()\n else:\n raise ValueError(f'Unknown action {cfg.action}')\n\n","repo_name":"cbosoft/simpleyacs","sub_path":"simpleyacs/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"42255781064","text":"import tqdm\nimport ipdb\nimport argparse, sys; sys.path.append('../..')\nimport random as rand\nimport torch\n\nfrom graphxai.gnn_models.node_classification.testing import GIN_3layer_basic, GCN_3layer_basic, GSAGE_3layer\n\ndef get_model(name):\n if name.lower() == 'gcn':\n model = GCN_3layer_basic(16, input_feat = 11, classes = 2)\n elif name.lower() == 'gin':\n model = GIN_3layer_basic(16, input_feat = 11, classes = 2)\n elif name.lower() == 'sage':\n # Get SAGE model\n model = GSAGE_3layer(16, input_feat = 11, classes = 2)\n else:\n OSError('Invalid model!')\n return model\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model', required=True, help = 'Name of model to train (GIN, GCN, or SAGE)')\nparser.add_argument('--dataset', required=True, help = 'Location of ShapeGGen dataset on which to train the model')\nparser.add_argument('--save_dir', default='./trained/', help='Directory to which to send trained models.')\nargs = parser.parse_args()\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel = get_model(name = args.model).to(device)","repo_name":"mims-harvard/GraphXAI","sub_path":"formal/ShapeGraph/train_models/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":121,"dataset":"github-code","pt":"85"} +{"seq_id":"7885021771","text":"import requests\nfrom functools import reduce\nimport re\nimport os\nfrom utils import save_json, load_json, make_dir, file_counter\nfrom time import sleep\nimport json\nfrom multiprocessing import Pool\n\nbase_url = 'https://ecatalog.smpcorp.com/V2/FS/api/'\n\n\nclass PartList:\n\n def extract_part_list(self, for_year=None):\n year_list = self.fetch_year_list()\n for year_item in year_list:\n print(year_item)\n if for_year is not None and year_item != for_year:\n continue\n make_dir('output/data/' + year_item)\n make_list = self.fetch_make_list(year_item)\n for make_item in make_list:\n print(year_item, make_item)\n make_dir('output/data/' + year_item + '/' + make_item.replace('/', '|'))\n model_list = self.fetch_model_list(year_item, make_item)\n\n for model_item in model_list:\n print(year_item, make_item, model_item)\n part_list_for_model = []\n output_file_path = 'output/data/' + year_item + '/' + make_item.replace('/',\n '|') + '/' + model_item.replace(\n '/', '|') + '.json'\n if os.path.exists(output_file_path):\n continue\n\n engine_list = self.fetch_engine_list(year_item, make_item, model_item)\n for engine_item in engine_list:\n parts_list = self.fetch_parts_list(year_item, make_item, model_item, engine_item)\n part_list_for_model.extend(parts_list)\n\n save_json(part_list_for_model, output_file_path)\n\n def fetch_year_list(self):\n response = requests.get(base_url + 'vehicle/years')\n response = json.loads(response.text)\n year_list = []\n for item in response:\n year_list.append(item['year'])\n return year_list\n\n def fetch_make_list(self, year):\n response = requests.get(base_url + 'vehicle/makes?year=' + year)\n response = json.loads(response.text)\n make_list = []\n for item in response:\n make_list.append(item['make'])\n return make_list\n\n def fetch_model_list(self, year, make):\n response = requests.get(base_url + 'vehicle/models?year=' + year + '&make=' + make)\n response = json.loads(response.text)\n model_list = []\n for item in response:\n model_list.append(item['model'])\n return model_list\n\n def fetch_engine_list(self, year, make, model):\n response = requests.get(base_url + 'vehicle/engines?year=' + year + '&make=' + make + '&model=' + model)\n response = json.loads(response.text)\n engine_list = response\n return engine_list\n\n def fetch_parts_list(self, year, make, model, engine):\n response = requests.get(base_url\n + 'part/partsearch'\n '?filter=ymme'\n '&filterType=n'\n '&searchType=p'\n '&imageSize=80'\n '&start=0'\n '&limit=1000000'\n '&sort=1'\n '&catFilter=-All-'\n '&yearFilter=' + year\n + '&makeFilter=' + make\n + '&modelFilter=' + model\n + '&engineFilter=' + engine['engine']\n + '&attrCodeFilter=-All-'\n '&attrValueFilter=-All-'\n )\n response = json.loads(response.text)\n for item in response:\n item['engine'] = engine\n return response\n\n\nclass PartDetails:\n\n def extract_part_details(self):\n # Get Available Parts List\n part_meta_list = []\n with os.scandir('output/data') as it1:\n for year_entry in it1:\n if os.path.isdir(year_entry.path):\n with os.scandir(year_entry.path) as it2:\n for make_entry in it2:\n if os.path.isdir(make_entry):\n print('\\r', year_entry.name, make_entry.name, end='')\n with os.scandir(make_entry.path) as it3:\n for model_entry in it3:\n if model_entry.name.endswith('.json'):\n data_file = load_json(model_entry.path)\n for part_item in data_file:\n part_number = part_item['basePart']\n file_name = 'output/parts/' + part_number + '.json'\n if not os.path.exists(file_name):\n part_meta_list.append({\n 'part_number': part_number,\n 'category': part_item['categoryName_en']\n })\n print()\n\n # Remove Duplicates\n temp = []\n for part_item in part_meta_list:\n item_exists = False\n for item in temp:\n if item['part_number'] == part_item['part_number']:\n item_exists = True\n break\n if not item_exists:\n temp.append(part_item)\n part_meta_list = temp\n\n print('===', len(part_meta_list), '===')\n\n pool = Pool(24)\n pool.map(self.fetch_and_export_part_details, part_meta_list)\n\n def fetch_and_export_part_details(self, meta):\n part_number = meta['part_number']\n output_file_name = 'output/parts/' + part_number + '.json'\n\n part_details = self.fetch_part_details(part_number)\n part_details['category'] = meta['category']\n part_details['images'] = self.fetch_images(part_number)\n\n save_json(part_details, output_file_name)\n # print(part_number)\n print('\\r', file_counter('output/parts'), end='')\n\n def fetch_part_details(self, part_number):\n print('\\r.', end='')\n response = requests.get(base_url\n + 'part/partselect'\n '?part=' + part_number\n + '&func=PART'\n '&vid=303910')\n response = json.loads(response.text)\n return response['pp']\n\n def fetch_images(self, part_number):\n # print('\\r..', end='')\n response = requests.get(base_url\n + 'image/getallimages'\n '?partNum=' + part_number\n + '&brand=FS'\n '&zoomFactor_sm=75'\n '&zoomFactor_md=360'\n '&zoomFactor_bg=960')\n response = json.loads(response.text)\n\n image_list = []\n for image_item in response:\n image_list.append(image_item['image_BG_Url'])\n return image_list\n\n def extract_competitor_oe(self):\n make_dir('output/parts/search_query')\n make_dir('output/parts/competitors')\n query_list = []\n for search_query in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',\n 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n query_list.append(search_query)\n\n pool = Pool(4)\n # pool.map(self.fetch_and_save_search_query, query_list)\n # pool.map(self.fetch_and_save_competitor_oe, query_list)\n self.fetch_and_save_competitor_oe('n')\n\n\n def fetch_and_save_search_query(self, search_query):\n output_file = 'output/parts/search_query/' + search_query + '.json'\n if os.path.exists(output_file):\n return\n\n response = requests.get('https://ecatalog.smpcorp.com/V2/FS/api/Vehicle/autosearch'\n '?func=PART'\n '&filter=' + search_query +\n '&count=100000000'\n '&searchType=X'\n '&site=FS')\n response = json.loads(response.text)\n print(search_query, ':', len(response))\n save_json(response, output_file)\n\n\n def extract_competitor_details(self):\n search_query_3 = []\n with os.scandir('output/parts/search_query') as it:\n for entry in it:\n if entry.name.endswith('.json'):\n data_file = load_json(entry.path)\n for item in data_file:\n query = item.split(' - ')[0][0:3]\n search_query_3.append(query)\n print('\\r', entry.name, end='')\n\n search_query_3 = list(dict.fromkeys(search_query_3))\n print(len(search_query_3))\n save_json(search_query_3, 'output/parts/search_query/_sub_3.json')\n\n # search_query_3 = load_json('output/parts/search_query/_sub_3.json')\n\n\n def fetch_and_save_competitor_oe(self, search_query):\n output_file = 'output/parts/competitors/' + search_query + '.json'\n if os.path.exists(output_file):\n return\n\n print('Search', search_query)\n response = requests.get(base_url\n + 'part/partsearch'\n '?filter=' + search_query + ' '\n + '&filterType=s'\n '&searchType=x'\n '&imageSize=80'\n '&start=0'\n '&limit=10000000'\n '&sort=1'\n '&catFilter=-All-'\n '&yearFilter=-All-'\n '&makeFilter=-All-'\n '&modelFilter=-All-'\n '&engineFilter=-All-'\n '&attrCodeFilter=-All-'\n '&attrValueFilter=-All-')\n response = json.loads(response.text)\n print(search_query, ':', len(response))\n for item in response:\n item.pop('brand')\n item.pop('brandLink')\n item.pop('maxRows')\n item.pop('partComment')\n item.pop('rowId')\n item.pop('categoryName_en')\n item.pop('imageUrl')\n item.pop('vehicleId')\n item.pop('site')\n item.pop('webBase')\n item.pop('webColumn_Id')\n save_json(response, output_file)\n\n","repo_name":"shrestha-prabin/4season-catalog-scraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":11076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29359036220","text":"from sklearn.utils.validation import check_is_fitted\n\nfrom .base import BaseGridder\nfrom .base.utils import check_data\nfrom .coordinates import get_region\n\n\nclass Chain(BaseGridder):\n \"\"\"\n Chain filtering operations to fit on each subsequent output.\n\n The :meth:`~verde.base.BaseGridder.filter` method of each element of the\n set is called with the outputs of the previous one. For gridders and trend\n estimators this means that each element fits the residuals (input data\n minus predicted data) of the previous one.\n\n When predicting data, the predictions of each step in the chain are added\n together. Steps that don't implement a\n :meth:`~verde.base.BaseGridder.predict` method are ignored.\n\n This provides a convenient way to chaining operations like trend estimation\n to a given gridder.\n\n Parameters\n ----------\n steps : list\n A list of ``('name', step)`` pairs where ``step`` is any verde\n class that implements a ``filter(coordinates, data, weights)`` method\n (including ``Chain`` itself).\n\n Attributes\n ----------\n region_ : tuple\n The boundaries (``[W, E, S, N]``) of the data used to fit the chain.\n Used as the default region for the :meth:`~verde.Chain.grid` and\n :meth:`~verde.Chain.scatter` methods.\n named_steps : dict\n A dictionary version of *steps* where the ``'name'`` strings are keys\n and the estimator/gridder/processor objects are the values.\n\n See also\n --------\n verde.Vector : Fit an estimator to each component of vector data\n\n \"\"\"\n\n def __init__(self, steps):\n super().__init__()\n self.steps = steps\n\n @property\n def named_steps(self):\n \"\"\"\n A dictionary version of steps.\n \"\"\"\n return dict(self.steps)\n\n def fit(self, coordinates, data, weights=None):\n \"\"\"\n Fit the chained estimators to the given data.\n\n Each estimator in the chain is fitted to the residuals of the previous\n estimator. The coordinates are preserved. Only the data values are\n changed.\n\n The data region is captured and used as default for the\n :meth:`~verde.Chain.grid` and :meth:`~verde.Chain.scatter` methods.\n\n All input arrays must have the same shape.\n\n Parameters\n ----------\n coordinates : tuple of arrays\n Arrays with the coordinates of each data point. Should be in the\n following order: (easting, northing, vertical, ...).\n data : array or tuple of arrays\n the data values of each data point. if the data has more than one\n component, *data* must be a tuple of arrays (one for each\n component).\n weights : none or array or tuple of arrays\n if not none, then the weights assigned to each data point. if more\n than one data component is provided, you must provide a weights\n array for each data component (if not none).\n\n Returns\n -------\n self\n Returns this estimator instance for chaining operations.\n\n \"\"\"\n self.region_ = get_region(coordinates[:2])\n args = coordinates, data, weights\n for _, step in self.steps:\n args = step.filter(*args)\n return self\n\n def predict(self, coordinates):\n \"\"\"\n Evaluates the data predicted by the chain on the given set of points.\n\n Predictions from each step in the chain are added together. Any step\n that doesn't implement a ``predict`` method is ignored.\n\n Requires a fitted gridder (see :meth:`~verde.Chain.fit`).\n\n Parameters\n ----------\n coordinates : tuple of arrays\n Arrays with the coordinates of each data point. Should be in the\n following order: (easting, northing, vertical, ...).\n\n Returns\n -------\n data : array\n The data values predicted on the given points.\n\n \"\"\"\n check_is_fitted(self, [\"region_\"])\n result = None\n for _, step in self.steps:\n if hasattr(step, \"predict\"):\n predicted = check_data(step.predict(coordinates))\n if result is None:\n result = [0 for i in range(len(predicted))]\n for i, pred in enumerate(predicted):\n result[i] += pred\n if len(result) == 1:\n return result[0]\n return tuple(result)\n","repo_name":"fatiando/verde","sub_path":"verde/chain.py","file_name":"chain.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","stars":539,"dataset":"github-code","pt":"85"} +{"seq_id":"19185485638","text":"from twilio.rest import Client\nfrom config import Config\n\n# Your Account SID from twilio.com/console\naccount_sid = Config.TWILIO_ACCOUNT_SID\n# Your Auth Token from twilio.com/console\nauth_token = Config.TWILIO_AUTH_TOKEN\nphoto_url = Config.EXAMPLE_PHOTO_URL\n\nclient = Client(account_sid, auth_token)\n\nmessage = client.messages.create(\n to=\"+11234567890\", \n from_=\"+10987654321\",\n body=\"John wants to gather with you, again!\")\n # media_url=photo_url)\n\nprint(message.sid)\n","repo_name":"johan456789/gather","sub_path":"send_sms.py","file_name":"send_sms.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4082542514","text":"import json\nimport os\nimport cv2\nimport torch\nimport numpy as np\nfrom solutions.solver import Solver\nfrom models.model import Model, ClassifyResNet\n\n\ndef post_process(probability, threshold, min_size):\n '''Post processing of each predicted mask, components with lesser number of pixels\n than `min_size` are ignored'''\n mask = cv2.threshold(probability, threshold, 1, cv2.THRESH_BINARY)[1]\n num_component, component = cv2.connectedComponents(mask.astype(np.uint8))\n predictions = np.zeros((256, 1600), np.float32)\n num = 0\n for c in range(1, num_component):\n p = (component == c)\n if p.sum() > min_size:\n predictions[p] = 1\n num += 1\n return predictions, num\n\n\ndef get_thresholds_minareas(json_path, fold=None):\n '''\n Obtain the optimal pixel threshold and optimal minimum connected domain of\n a specific fold of each category or the average optimal pixel threshold\n and average optimal minimum connected domain of all folds\n '''\n with open(json_path, encoding='utf-8') as json_file:\n result = json.load(json_file)\n if fold != None:\n thresholds, minareas = result[str(fold)]['best_thresholds'], result[str(fold)]['best_minareas']\n else:\n thresholds, minareas = result['mean']['best_thresholds'], result['mean']['best_minareas']\n return thresholds, minareas\n\n\nclass Get_Classify_Results():\n def __init__(self, model_name, fold, model_path, class_num=4, tta_flag=False):\n self.model_name = model_name\n self.fold = fold\n self.model_path = model_path\n self.class_num = class_num\n self.tta_flag = tta_flag\n \n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n self.classify_model = ClassifyResNet(model_name, encoder_weights=None)\n if torch.cuda.is_available():\n self.classify_model = torch.nn.DataParallel(self.classify_model)\n\n self.classify_model.to(self.device)\n\n self.classify_model_path = os.path.join(self.model_path, '%s_classify_fold%d_best.pth' % (self.model_name, self.fold))\n self.solver = Solver(self.classify_model)\n self.classify_model = self.solver.load_checkpoint(self.classify_model_path)\n self.classify_model.eval()\n\n def get_classify_results(self, images, thrshold=0.5):\n if self.tta_flag:\n predict_classes = self.solver.tta(images, seg=False)\n else:\n predict_classes = self.solver.forward(images)\n predict_classes = predict_classes > thrshold\n return predict_classes\n\n\nclass Get_Segment_Results():\n def __init__(self, model_name, fold, model_path, class_num=4, tta_flag=False):\n self.model_name = model_name\n self.fold = fold\n self.model_path = model_path\n self.class_num = class_num\n self.tta_flag = tta_flag\n\n self.segment_model = Model(self.model_name, encoder_weights=None).create_model()\n self.segment_model_path = os.path.join(self.model_path, '%s_fold%d_best.pth' % (self.model_name, self.fold))\n self.solver = Solver(self.segment_model)\n self.segment_model = self.solver.load_checkpoint(self.segment_model_path)\n self.segment_model.eval()\n\n self.json_path = os.path.join(self.model_path, '%s_result.json' % self.model_name)\n self.best_thresholds, self.best_minareas = get_thresholds_minareas(self.json_path, self.fold)\n\n def get_segment_results(self, images, process_flag=True):\n if self.tta_flag:\n predict_masks = self.solver.tta(images)\n else:\n predict_masks = self.solver.forward(images)\n if process_flag:\n for index, predict_masks_classes in enumerate(predict_masks):\n for each_class, pred in enumerate(predict_masks_classes):\n pred_binary, _ = post_process(pred.detach().cpu().numpy(), self.best_thresholds[each_class], self.best_minareas[each_class])\n predict_masks[index, each_class] = torch.from_numpy(pred_binary)\n return predict_masks\n\n\nclass Classify_Segment_Fold():\n def __init__(self, classify_fold, seg_fold, model_path, class_num=4, tta_flag=False, kaggle=0):\n\n self.classify_fold = classify_fold\n self.seg_fold = seg_fold\n self.model_path = model_path\n self.class_num = class_num\n for (model_name, fold) in self.classify_fold.items():\n if kaggle == 0:\n pth_path = os.path.join(self.model_path, model_name)\n else:\n pth_path = self.model_path \n self.classify_model = Get_Classify_Results(model_name, fold, pth_path, self.class_num, tta_flag=tta_flag)\n for (model_name, fold) in self.classify_fold.items():\n if kaggle == 0:\n pth_path = os.path.join(self.model_path, model_name)\n else:\n pth_path = self.model_path\n self.segment_model = Get_Segment_Results(model_name, fold, pth_path, self.class_num, tta_flag=tta_flag)\n\n def classify_segment(self, images):\n\n predict_classes = self.classify_model.get_classify_results(images)\n predict_masks = self.segment_model.get_segment_results(images)\n for index, predicts in enumerate(predict_classes):\n for each_class, pred in enumerate(predicts):\n if pred == 0:\n predict_masks[index, each_class, ...] = 0\n return predict_masks\n\n\nclass Classify_Segment_Folds():\n def __init__(self, classify_folds, segment_folds, model_path, class_num=4, tta_flag=False, kaggle=0):\n\n self.classify_folds = classify_folds\n self.segment_folds = segment_folds\n self.model_path = model_path\n self.class_num = class_num\n self.tta_flag = tta_flag\n self.kaggle = kaggle\n\n self.classify_models, self.segment_models = list(), list()\n self.get_classify_segment_models()\n\n def get_classify_segment_models(self):\n\n for (model_name, fold) in self.classify_folds.items():\n if self.kaggle == 0:\n pth_path = os.path.join(self.model_path, model_name)\n else: \n pth_path = self.model_path \n self.classify_models.append(Get_Classify_Results(model_name, fold, pth_path, self.class_num, tta_flag=self.tta_flag))\n for (model_name, fold) in self.segment_folds.items():\n if self.kaggle == 0:\n pth_path = os.path.join(self.model_path, model_name)\n else: \n pth_path = self.model_path\n self.segment_models.append(Get_Segment_Results(model_name, fold, pth_path, self.class_num, tta_flag=self.tta_flag))\n\n def classify_segment_folds(self, images):\n\n results = torch.zeros(images.shape[0], self.class_num, images.shape[2], images.shape[3])\n for classify_model, segment_model in zip(self.classify_models, self.segment_models):\n\n predict_classes = classify_model.get_classify_results(images)\n\n predict_masks = segment_model.get_segment_results(images)\n for index, predicts in enumerate(predict_classes):\n for each_class, pred in enumerate(predicts):\n if pred == 0:\n predict_masks[index, each_class, ...] = 0\n results += predict_masks.detach().cpu()\n vote_model_num = len(self.segment_folds)\n vote_ticket = round(vote_model_num / 2.0)\n results = results > vote_ticket\n\n return results\n\n\nclass Classify_Segment_Folds_Split():\n def __init__(self, classify_folds, segment_folds, model_path, class_num=4, tta_flag=False, kaggle=0):\n\n self.classify_folds = classify_folds\n self.segment_folds = segment_folds\n self.model_path = model_path\n self.class_num = class_num\n self.tta_flag = tta_flag\n self.kaggle = kaggle\n\n self.classify_models, self.segment_models = list(), list()\n self.get_classify_segment_models()\n\n def get_classify_segment_models(self):\n\n for (model_name, fold) in self.classify_folds.items():\n if self.kaggle == 0:\n pth_path = os.path.join(self.model_path, model_name)\n else: \n pth_path = self.model_path \n self.classify_models.append(Get_Classify_Results(model_name, fold, pth_path, self.class_num, tta_flag=self.tta_flag))\n for (model_name, fold) in self.segment_folds.items():\n if self.kaggle == 0:\n pth_path = os.path.join(self.model_path, model_name)\n else: \n pth_path = self.model_path\n self.segment_models.append(Get_Segment_Results(model_name, fold, pth_path, self.class_num, tta_flag=self.tta_flag))\n\n def classify_segment_folds(self, images, average_strategy=False):\n\n classify_results = torch.zeros(images.shape[0], self.class_num)\n segment_results = torch.zeros(images.shape[0], self.class_num, images.shape[2], images.shape[3])\n\n for classify_index, classify_model in enumerate(self.classify_models):\n classify_result_fold = classify_model.get_classify_results(images)\n classify_results += classify_result_fold.detach().cpu().squeeze().float()\n classify_vote_model_num = len(self.classify_folds)\n classify_vote_ticket = round(classify_vote_model_num / 2.0)\n classify_results = classify_results > classify_vote_ticket\n\n if average_strategy:\n for segment_index, segment_model in enumerate(self.segment_models):\n segment_result_fold = segment_model.get_segment_results(images, process_flag=False)\n segment_results += segment_result_fold.detach().cpu()\n average_thresholds, average_minareas = get_thresholds_minareas(os.path.join(self.model_path, 'result.json'))\n segment_results = segment_results/len(self.segment_folds)\n for index, predict_masks_classes in enumerate(segment_results):\n for each_class, pred in enumerate(predict_masks_classes):\n pred_binary, _ = post_process(pred.detach().cpu().numpy(),\n average_thresholds[each_class],\n average_minareas[each_class])\n segment_results[index, each_class] = torch.from_numpy(pred_binary)\n\n else:\n for segment_index, segment_model in enumerate(self.segment_models):\n segment_result_fold = segment_model.get_segment_results(images)\n segment_results += segment_result_fold.detach().cpu()\n segment_vote_model_num = len(self.segment_folds)\n segment_vote_ticket = round(segment_vote_model_num / 2.0)\n segment_results = segment_results > segment_vote_ticket\n\n for batch_index, classify_result in enumerate(classify_results):\n segment_results[batch_index, ~classify_result, ...] = 0\n\n return segment_results\n\n\nclass Segment_Folds():\n def __init__(self, model_name, n_splits,\n model_path, class_num=4, tta_flag=False):\n\n self.model_name = model_name\n self.n_splits = n_splits\n self.model_path = model_path\n self.class_num = class_num\n self.tta_flag = tta_flag\n\n self.segment_models = list()\n self.get_segment_models()\n\n def get_segment_models(self):\n for fold in self.n_splits:\n self.segment_models.append(Get_Segment_Results(self.model_name,\n fold,\n self.model_path,\n self.class_num,\n tta_flag=self.tta_flag))\n\n def segment_folds(self, images):\n\n results = torch.zeros(images.shape[0],\n self.class_num,\n images.shape[2],\n images.shape[3])\n for segment_model in self.segment_models:\n\n predict_masks = segment_model.get_segment_results(images)\n results += predict_masks.detach().cpu()\n vote_model_num = len(self.n_splits)\n vote_ticket = round(vote_model_num / 2.0)\n results = results > vote_ticket\n\n return results","repo_name":"avdeenkodmitry/steel-defect-detection","sub_path":"solutions/classify_segment.py","file_name":"classify_segment.py","file_ext":"py","file_size_in_byte":12470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"11284635697","text":"import string\nimport random\n\ndef remove_punctuation(var):\n no_punct = \"\"\n for item in var:\n if item not in string.punctuation:\n no_punct += item\n return no_punct\n\n\n\n\n# no longer in use.\n'''def lousy_plasma():\n empty_string = \"\" \n input1 = input(\"what is your sentence?\").strip()\n input1 = remove_punctuation(input1).split( )\n for item in input1:\n if item in dict1.keys():\n empty_string += random.choice(dict1[item]).upper() + \" \" \n else:\n empty_string += item + \" \"\n print(empty_string)\n from os import system\n system(\"say -i -v Fiona \" + \"\\\"\" + empty_string + \"\\\"\")'''\n\n\n \ndef word_changer(words):\n words = words.strip()\n words_without_punct = remove_punctuation(words).split()\n result = \"\"\n c = 0\n\n for item in words_without_punct:\n if item in dict1.keys():\n if c % 2 == 0:\n result += random.choice(dict1[item]).upper() \n\n else:\n result += item \n c += 1\n else:\n result += item \n result += \" \"\n return(result)\n\n\nt = open('thesaurus', 'r')\ndict1 = {}\nfor line in t:\n split_words = line.split(\",\")\n key = split_words.pop(0)\n dict1.update({key:split_words})\n\n\nbad_blood_lyrics = open('bad_blood.txt', 'r')\nlyrics = bad_blood_lyrics.read()\n\nprint(word_changer(lyrics))\n","repo_name":"brandon-tutoring/isabella_lousy_plasma","sub_path":"lousy_plasma0.py","file_name":"lousy_plasma0.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19815058618","text":"from recidiviz.big_query.big_query_view import SimpleBigQueryViewBuilder\nfrom recidiviz.calculator.query.state import dataset_config\nfrom recidiviz.utils.environment import GCP_PROJECT_STAGING\nfrom recidiviz.utils.metadata import local_project_id_override\n\nPERSON_RECORD_VIEW_NAME = \"person_record\"\n\nPERSON_RECORD_DESCRIPTION = (\n \"View that combines the client and resident records together\"\n)\n\nPERSON_RECORD_QUERY_TEMPLATE = \"\"\"\nSELECT\n person_external_id,\n state_code,\n person_name,\n officer_id,\n supervision_level AS correctional_level,\n supervision_start_date AS start_date,\n expiration_date AS end_date,\n district AS location,\n pseudonymized_id,\n all_eligible_opportunities\nFROM `{project_id}.{workflows_views_dataset}.client_record_materialized` client_record\n\nUNION ALL\n\nSELECT\n person_external_id,\n state_code,\n person_name,\n officer_id,\n custody_level AS correctional_level,\n admission_date AS start_date,\n release_date AS end_date,\n facility_id AS location,\n pseudonymized_id,\n all_eligible_opportunities\nFROM `{project_id}.{workflows_views_dataset}.resident_record_materialized` resident_record\n\"\"\"\n\nPERSON_RECORD_VIEW_BUILDER = SimpleBigQueryViewBuilder(\n dataset_id=dataset_config.WORKFLOWS_VIEWS_DATASET,\n view_id=PERSON_RECORD_VIEW_NAME,\n view_query_template=PERSON_RECORD_QUERY_TEMPLATE,\n description=PERSON_RECORD_DESCRIPTION,\n workflows_views_dataset=dataset_config.WORKFLOWS_VIEWS_DATASET,\n should_materialize=True,\n)\n\nif __name__ == \"__main__\":\n with local_project_id_override(GCP_PROJECT_STAGING):\n PERSON_RECORD_VIEW_BUILDER.build_and_print()\n","repo_name":"Recidiviz/pulse-data","sub_path":"recidiviz/calculator/query/state/views/workflows/person_record.py","file_name":"person_record.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"85"} +{"seq_id":"814461513","text":"import logging\n\n\nlogger = logging.getLogger(\"api_logger\")\nlogger.setLevel(logging.INFO)\nlogger_handler = logging.FileHandler(\"./logs/api.log\")\nlogger_formatter = logging.Formatter(\"%(asctime)s [%(levelname)s] %(message)s\")\nlogger_handler.setFormatter(logger_formatter)\nlogger.addHandler(logger_handler)\n\n","repo_name":"AgeHT70/course_work_3","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"11592374220","text":"# 정렬된 배열의 정합 2\n# Constraint\n# 추가 배열 공간 할당 없음\n# nums1, nums2 크기 제한 없음\n# nums1, nums2 요소는 정렬되어있음\n# Tim sort 이용 \nfrom typing import List\n\ndef merge(nums1: List[int], m: int, nums2:List[int], n:int) -> List[int]:\n for i, nums1_item in enumerate(nums1):\n if nums1_item>nums2[0]:\n nums1[i] = nums2[0]\n nums2[0] = nums1_item\n\n for k, item in enumerate(nums2[1:], start=1):\n if nums1_item<=item:\n nums2[k-1] = nums1_item\n break\n\n nums2[k-1] = nums2[k]\n\n return nums1, nums2\n\nprint(merge([1,3],2,[2,4],2))\n","repo_name":"moonbaaang/Algorithm-DataStructure","sub_path":"1. Array/1-7 sortedArrayMerge.py","file_name":"1-7 sortedArrayMerge.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32805870311","text":"from pathlib import Path\n\nimport pandas as pd\nfrom invoke import task\n\nfrom porforum.message.scrape import get_thread_message_generator\nfrom porforum.thread.scrape import get_thread_data, get_topic_data\n\nDATA_PATH = Path(\"data\")\nDATA_PATH.mkdir(exist_ok=True)\nMESSAGES_PATH = DATA_PATH / \"messages\"\nMESSAGES_PATH.mkdir(exist_ok=True)\n\n\n@task(aliases=[\"dt\"])\ndef download_thread_data(cli, with_topics=True):\n thread_data = get_thread_data()\n df = pd.DataFrame(thread_data).set_index(\"thread_id\")\n df.to_parquet(DATA_PATH / \"threads.parquet\")\n if with_topics:\n topic_data = get_topic_data()\n topic_df = pd.DataFrame(topic_data).set_index(\"thread_id\")[[\"topic\"]]\n topic_df.to_parquet(DATA_PATH / \"topics.parquet\")\n\n\n@task(aliases=[\"dm\"])\ndef download_message_data(cli, update=False, verbose=True):\n thread_dict = pd.read_parquet(DATA_PATH / \"threads.parquet\")[\"thread_url\"].to_dict()\n if not update:\n [(thread_dict.pop(int(p.stem))) for p in MESSAGES_PATH.iterdir()]\n for thread_id, thread_data in get_thread_message_generator(\n thread_dict, verbose=verbose\n ):\n thread_data = pd.DataFrame(thread_data)\n if not thread_data.empty:\n thread_data.astype({\"prev_id\": \"string\"}).set_index(\"id\").to_parquet(\n MESSAGES_PATH / f\"{thread_id}.parquet\"\n )\n","repo_name":"papsebestyen/financial_mining","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"16643774748","text":"import sys\nsys.path.append('features/login/features/utils')\nimport random\nfrom features.login.features.utils.environment import *\nfrom features.login.features.utils.global_queries import *\n\n\ndriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\ndriver.implicitly_wait(5)\n\n@given(\"I am on the login page\")\ndef step_impl(context):\n driver.get(\"https://voila.id/account/login/\")\n take_screenshot(driver)\n\n@when(\"I enter my email in email field and password in password field\")\ndef step_impl(context):\n element_id_login_email(driver).send_keys(data_email())\n element_id_login_password(driver).send_keys(data_password())\n\n@when('I click the login button')\ndef step_impl(context):\n element_class_login_button(driver).click()\n\n@then(\"I Should be redirected to voila.id/account\")\ndef step_impl(context):\n wait_webdriver_url(driver,\"https://voila.id/account\")\n current_url = get_current_url(driver)\n if current_url == \"https://voila.id/account\":\n take_screenshot(driver)\n else:\n raise NotImplementedError(u'STEP: I Should be redirected to voila.id/account')\n \n\n\n@given(u'I am on the homepage of voila.id')\ndef step_impl(context):\n sleep(10)\n try:\n driver.find_element(\"css selector\",'button[aria-label=\"close\"]').click()\n except:\n print(\"No Pop Up Deals\")\n driver.find_element('xpath','/html/body/div[3]/header/div[2]/div[1]/div/div/div[1]/a').click() \n \n current_url = get_current_url(driver)\n if current_url == \"https://voila.id/\":\n take_screenshot(driver)\n else:\n raise NotImplementedError(u'STEP: Given I am on the homepage of voila.id')\n\n@when(u'I clicked on one of the product listed')\ndef step_impl(context):\n # try:\n driver.find_element('xpath','//*[@id=\"main-menu\"]/div/div/nav/ul/li[4]/a').click()\n first_product = driver.find_element('xpath','//*[@id=\"shopify-section-collection-template-boost-pfs-filter\"]/div[2]/div[1]/div[2]/div[3]/div[1]/div/div[1]/a')\n # wait_webdriver_element_clickable(driver,\"css selector\",'a[tabindex=\"0\"]')\n # click_me = driver.find_elements(\"css selector\",'a[tabindex=\"0\"]')\n # click_random = random.choice(click_me)\n link_of_click = first_product.get_attribute(\"href\")\n first_product.click()\n # click_random.click()\n context.link_of_click = link_of_click\n # except:\n # raise NotImplementedError(u'It redirect to the page of the product')\n\n\n@then(u'It redirect to the page of the product')\ndef step_impl(context):\n print(context.link_of_click)\n current_url = get_current_url(driver)\n clicked_url = context.link_of_click\n if current_url == clicked_url:\n take_screenshot(driver)\n else:\n raise NotImplementedError(u'STEP: Then It redirect to the page of the product')\n context.clicked_url = clicked_url\n\n\n@given(u'I am on the page of selected product')\ndef step_impl(context):\n try:\n take_screenshot(driver)\n except:\n raise NotImplementedError(u'STEP: Given I am on the page of selected product')\n\n\n@when(u'I click + Keranjang')\ndef step_impl(context):\n sleep(5)\n driver.find_element(\"css selector\",'button[data-type=\"addtocart\"]').click()\n\n\n@then(u'I should have an popped up windows of Produk berhasil ditambah!')\ndef step_impl(context):\n check_modal = driver.find_element(\"class name\",\"tt-modal-messages\")\n if check_modal != \"\":\n take_screenshot(driver)\n else:\n raise NotImplementedError(u'STEP: Then I should have an popped up windows of Produk berhasil ditambah!')\n\n@given(u'I am on the popped up page of Produk berhasil ditambah!')\ndef step_impl(context):\n try:\n take_screenshot(driver)\n except: \n raise NotImplementedError(u'STEP: Given I am on the popped up page of Produk berhasil ditambah!')\n\n\n@when(u'I click on Beli')\ndef step_impl(context):\n try:\n driver.find_element(\"partial link text\",'BELI').click()\n except:\n raise NotImplementedError(u'STEP: When I click on Beli')\n\n\n@then(u'I should be redirected to checkouts page')\ndef step_impl(context):\n try:\n driver.find_element(\"css selector\",'h2.n8k95w1._1fragema3.n8k95w3')\n except:\n raise NotImplementedError(u'STEP: Then I should be redirected to checkouts page')\n\n\n@given(u'I am on the checkout page')\ndef step_impl(context):\n try:\n take_screenshot(driver)\n # driver.get(\"https://voila.id/checkouts/c/c8d5ca3f72ce06a5911422f13e4d9953/information?_ga=2.16386294.1789729160.1681838703-1173728324.1681838620\")\n except:\n raise NotImplementedError(u'STEP: Given I am on the checkout page')\n\n\n@when(u'I type Arief in Nama Depan field')\ndef step_impl(context):\n try:\n login_again = driver.find_element('css selector','a.s2kwpi1._1fragema3._1fragemah._1fragemap.s2kwpi2._1fragemaa')\n login_again.click()\n element_id_login_email(driver).send_keys(data_email())\n element_id_login_password(driver).send_keys(data_password())\n element_class_login_button(driver).click()\n except:\n print(\"Already logged in and not logged out in the middle\")\n try:\n first_name = driver.find_element(\"id\",'TextField1') \n first_name.clear()\n first_name.send_keys(data_first_name())\n except:\n raise NotImplementedError(u'STEP: When I type Arief in Nama Depan field')\n\n\n\n@when(u'I type Chaerudin in Nama Belakang field')\ndef step_impl(context):\n try:\n last_name = driver.find_element(\"id\",'TextField2')\n last_name.clear()\n last_name.send_keys(data_last_name())\n except:\n raise NotImplementedError(u'STEP: When I type Chaerudin in Nama Belakang field')\n\n\n@when(u'I type [Arief Chaerudin]-[Candidate QA] in Alamat field')\ndef step_impl(context):\n try:\n address = driver.find_element(\"id\",'TextField3')\n address.clear()\n address.send_keys(data_address())\n except:\n raise NotImplementedError(u'STEP: When I type [Arief Chaerudin]-[Candidate QA] in Alamat field')\n\n\n@when(u'I type [Arief Chaerudin]-[Candidate QA] in Kota Kecamatan field')\ndef step_impl(context):\n try:\n city_state = driver.find_element(\"id\",'TextField5')\n city_state.clear()\n city_state.send_keys(data_address())\n except:\n raise NotImplementedError(u'I type [Arief Chaerudin]-[Candidate QA] in Kota Kecamatan field')\n\n\n@when(u'I type 13950 in Kode Pos field')\ndef step_impl(context):\n try:\n zip_code_field = driver.find_element(\"id\",\"TextField6\") \n zip_code_field.clear()\n zip_code_field.send_keys(zip_code())\n except:\n raise NotImplementedError(u'I type 13950 in Kode Pos field')\n\n\n@when(u'I click the dropdown and select Daerah Khusus Ibukota Jakarta')\ndef step_impl(context):\n # try:\n select_value = Select(driver.find_element(\"name\",\"zone\"))\n select_value.select_by_value(data_region())\n # except:\n # raise NotImplementedError(u'I click the dropdown and select Daerah Khusus Ibukota Jakarta')\n\n\n@when(u'I type 089672300149 in No Handphone field')\ndef step_impl(context):\n try:\n phone_number = driver.find_element(\"id\",\"TextField7\")\n phone_number.clear()\n phone_number.send_keys(data_phone_number())\n except:\n raise NotImplementedError(u'I type 089672300149 in No Handphone field')\n\n\n@when(u'I click lanjut ke pengiriman')\ndef step_impl(context):\n try:\n driver.find_element(\"css selector\",'button[type=\"submit\"]').click()\n except:\n raise NotImplementedError(u'I click lanjut ke pengiriman')\n\n\n@then(u'The Nama Depan textbox changed to Arief')\ndef step_impl(context):\n try:\n value_confirmation(driver,'id','TextField1',data_first_name())\n except:\n raise NotImplementedError(u'STEP: Then The Nama Depan textbox changed to Arief')\n\n\n@then(u'The Nama Belakang textbox changed to Chaerudin')\ndef step_impl(context):\n try:\n value_confirmation(driver,'id','TextField2',data_last_name())\n except:\n raise NotImplementedError(u'STEP: Then The Nama Belakang textbox changed to Chaerudin')\n\n\n@then(u'The Alamat textbox changed to [Arief Chaerudin]-[Candidate QA]')\ndef step_impl(context):\n try:\n value_confirmation(driver,'id','TextField3',data_address())\n except:\n raise NotImplementedError(u'STEP: Then The Alamat textbox changed to [Arief Chaerudin]-[Candidate QA]')\n\n\n@then(u'The Kota Kecamatan textbox changed to [Arief Chaerudin]-[Candidate QA]')\ndef step_impl(context):\n # try:\n value_confirmation(driver,'id','TextField5',data_address())\n # except:\n # raise NotImplementedError(u'STEP: Then The Kota Kecamatan textbox changed to [Arief Chaerudin]-[Candidate QA]')\n\n\n@then(u'The Kode Pos textbox changed to 13950')\ndef step_impl(context):\n try:\n value_confirmation(driver,'id','TextField6',zip_code())\n except:\n raise NotImplementedError(u'STEP: Then The Kode Pos textbox changed to 13950')\n\n\n@then(u'The Dropdown value changed to Daerah Khusus Ibukota Jakarta')\ndef step_impl(context):\n try:\n value_confirmation(driver,'name','zone',data_region())\n except:\n raise NotImplementedError(u'STEP: Then The Dropdown value changed to Daerah Khusus Ibukota Jakarta')\n\n\n@then(u'The No Handphone textbox changed to 089672300149')\ndef step_impl(context):\n # try:0896-7230-0149\n phone_parse = data_phone_number()\n phone_parse = phone_parse[:4] + \"-\" + phone_parse[4:8] + \"-\" + phone_parse[8:]\n value_confirmation(driver,'id','TextField7',phone_parse)\n # except:\n # raise NotImplementedError(u'STEP: Then The No Handphone textbox changed to 089672300149')\n\n\n@then(u'Redirected to shipping page')\ndef step_impl(context):\n shipment_method = driver.find_element('css selector','section[aria-label=\"Metode pengiriman\"]')\n if shipment_method !=\"\":\n print(shipment_method)\n else:\n raise NotImplementedError(u'STEP: Then Redirected to shipping page')\n\n\n@given(u'I am on the shipping page')\ndef step_impl(context):\n try:\n take_screenshot(driver)\n except:\n raise NotImplementedError(u'STEP: I am on the shipping page')\n\n@when(u'I click radio button value JNT in metode pengiriman')\ndef step_impl(context):\n # try:\n shipment_radio = driver.find_element('xpath','/html/body/div[1]/div/div/div/div[1]/div/div[2]/div/div/div/div[2]/div/div/div/main/form/div[1]/div/div/div[1]/section/div/div[2]/fieldset/div[2]/div[2]/label/div/div[2]/div[1]/p')\n shipment_radio.click() \n # except:\n # raise NotImplementedError(u'STEP: I click radio button value JNT in metode pengiriman')\n\n@when(u'I click Lanjut ke Pembayaran')\ndef step_impl(context):\n try:\n driver.find_element(\"css selector\",'button[type=\"submit\"]').click()\n except:\n raise NotImplementedError(u'STEP: I click Lanjut ke Pembayaran')\n\n\n@then(u'I saw the radio button value switched to JNT')\ndef step_impl(context):\n radio_button_JNT = driver.find_element('xpath','/html/body/div[1]/div/div/div/div[1]/div/div[2]/div/div/div/div[2]/div/div/div/main/form/div[1]/div/div/div[1]/section/div/div[2]/fieldset/div[2]/div[2]/label/div/div[2]/div[1]/p')\n if radio_button_JNT.is_selected():\n take_screenshot(driver)\n else:\n raise NotImplementedError(u'STEP: Then I saw the radio button value switched to JNT')\n\n@then(u'I get redirected to payment page')\ndef step_impl(context):\n payment_page = driver.find_element('css selector','section[aria-label=\"Pembayaran\"]')\n if payment_page !=\"\":\n print(payment_page)\n else:\n raise NotImplementedError(u'STEP: Then I get redirected to payment page')\n\n@given(u'I am on the payment page')\ndef step_impl(context):\n try:\n take_screenshot(driver)\n except:\n raise NotImplementedError(u'STEP: Given I am on the payment page')\n\n\n@when(u'I click the radio button value bank transfer')\ndef step_impl(context):\n try:\n driver.find_element('id','basic-customManualPayment-61481550008').click()\n total_price = driver.find_element('xpath','//*[@id=\"app\"]/div/div/div/div[1]/div/aside/div[2]/div/div/div/section/div[2]/div[3]/div[2]/div/div/strong').get_attribute()\n total_price = re.sub(\"[^0-9]\", \"\", total_price)\n context.total_price = total_price\n except:\n raise NotImplementedError(u'STEP: When I click the radio button value bank transfer')\n\n\n@when(u'I click the Selesaikan Pesanan button')\ndef step_impl(context):\n try:\n driver.find_element(\"css selector\",'button[type=\"submit\"]').click()\n except:\n raise NotImplementedError(u'STEP: When I click the Selesaikan Pesanan button')\n\n\n@then(u'I saw the radio button value switched to bank transfer')\ndef step_impl(context):\n try:\n radio_button_payment = driver.find_element('id','basic-customManualPayment-61481550008')\n if radio_button_payment.is_selected():\n take_screenshot(driver)\n except: \n raise NotImplementedError(u'STEP: Then I saw the radio button value switched to bank transfer')\n\n@then(u'I get redirected to thank you page with the right amount')\ndef step_impl(context):\n thank_you_page = driver.find_element('class name','thank-you__additional-content')\n final_total_price = driver.find_element('class name','payment-due__price skeleton-while-loading--lg')\n final_total_price.get_attribute()\n final_total_price = re.sub(\"[^0-9]\", \"\", final_total_price)\n compare_total_price = context.total_price\n if thank_you_page != '' and compare_total_price == final_total_price:\n take_screenshot(driver)\n else:\n raise NotImplementedError(u'STEP: Then I get redirected to thank you page')","repo_name":"arief0408/Web_test_selenium","sub_path":"features/login/features/steps/login_steps.py","file_name":"login_steps.py","file_ext":"py","file_size_in_byte":13643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13908924212","text":"LBS_PER_KG = 2.2046\r\nINCHES_PER_METER = 39.3701\r\n\r\ndef calc_bmi(weight_kg, height_m):\r\n return weight_kg / height_m**2\r\n\r\ndef input_float(prompt, min_value = None):\r\n done = False\r\n while not done:\r\n try:\r\n txt = input(prompt)\r\n value = float(txt)\r\n if min_value == None or min_value <= value:\r\n done = True\r\n else:\r\n print(f\"Error: Number must be > {min_value}\")\r\n except ValueError:\r\n print(\"That was not a number, please try again.\")\r\n\r\n return value \r\n\r\ndef main():\r\n done = False\r\n while not done:\r\n weight_lbs = input_float(\"Please enter weight (pounds): \", min_value = 0)\r\n height_in = input_float(\"Please enter height (inches): \", min_value = 0)\r\n\r\n weight_kg = weight_lbs / LBS_PER_KG\r\n height_m = height_in / INCHES_PER_METER\r\n\r\n bmi = calc_bmi(weight_kg, height_m)\r\n\r\n if bmi > 32:\r\n print(\"Overload situation, shutdown for maint.\")\r\n done = True\r\n continue\r\n\r\n print(f\"BMI is {bmi:.1f}\")\r\n again = input(\"Go again (y/n)? \")\r\n if again != \"y\":\r\n done = True\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"chrismreddy/CIS3680","sub_path":"bmi2.py","file_name":"bmi2.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4416193968","text":"PNG_header = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0X0a, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44]\n\nwith open(\"image.png\", \"rb\") as f:\n data = f.read()\n\nkey = \"\"\nfor i in range(len(PNG_header)):\n key += chr(PNG_header[i] ^ data[i])\n\nres = []\nfor i in range(len(data)):\n res.append(data[i] ^ ord(key[i % len(key)]))\n\nwith open(\"res.png\", \"wb\") as f:\n f.write(bytearray(res))\n","repo_name":"anijackich/CTF-WriteUps","sub_path":"2021/InnoCTF Juniors/crypto/WhiteBox/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"30043272522","text":"from py.runLca.utils import runMplusWithSaveFile, analyzeOutput, prepareInputFile, rollBehaviors, deleteInputAndOutpusFiles, getSubjectsArrNames, subjects, analyzeOutputToGetMothersOfEachSubjectLCAGroup, prepareInputFileWithName, NoEmptyObservations\nimport logging\nimport pathlib\nimport sys\nimport os\nimport time\nfrom datetime import datetime\nfrom datetime import datetime as dt\nfrom datetime import timedelta\nimport multiprocessing as mp\nfrom multiprocessing import Process, freeze_support\nimport threading\nimport logging\nimport linecache\nimport csv\nimport pandas as pd\n# REPLACE GELEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\nnumberOfMachines = 10\nmachineNumber = 10\n\n\ndef main():\n\n error = \"\"\n\n file = open(\"C:\\\\TEMP\\\\mplus\\\\errors.txt\", \"w+\")\n file. truncate(0)\n file. close()\n\n # getSubjectsArrNames()\n gelem = pd.read_csv('C:\\\\TEMP\\\\mplus\\\\gelem_with_vars_names.csv')\n lcaGroups = pd.read_csv(\n 'C:\\\\TEMP\\\\mplus\\\\motherLCAfilteredMinGroup15andUp.csv', na_filter=False)\n for index, row in lcaGroups.iterrows():\n iterName = 'lca_'+str(row['iteration'])\n lcaVars = row['vars']\n if (NoEmptyObservations(gelem, lcaVars.replace(\"'\", \"\").replace(\")\", \"\").replace(\"(\", \"\").replace(\" \", \"\").split(','))):\n runMplusOnPermutaion(lcaVars, row['iteration'])\n break\n\n # with open(\"C:\\\\TEMP\\\\mplus\\\\motherLCAfilteredMinGroup15andUp.csv\", \"r\", newline='') as text_file:\n # writer = csv.writer(text_file)\n # writer.writerow([\"iteration\", \"file name\", \"vars\",\n # \"# vars\", \"c1\", \"c2\", \"c3\"])\n # text_file.close()\n\n # machineRange = preparePermFileRanges('permFile.txt', machineNumber)\n\n # t1 = dt.now()\n # for i in machineRange:\n # vars = extractVarsFromPermFile('permFile.txt', i)\n # print(vars)\n # runMplusOnPermutaion(vars, i)\n\n\ndef runMplusOnPermutaion(vars, c):\n t2 = datetime.now()\n print(t2.strftime(\"%H:%M:%S\") + \" iteration: #\"+str(c) +\n ': running mplus on vars: '+str(vars))\n try:\n prepareInputFileWithName(vars, c)\n runMplusWithSaveFile(vars, c)\n analyzeOutputToGetMothersOfEachSubjectLCAGroup(c, len(vars*2), vars)\n return 4\n deleteInputAndOutpusFiles(c)\n print('done iteration '+str(c))\n except Exception as e:\n # print(\"FAILED! failed vars: \"+str(vars)+\"\\n\"+\"error:\"+\"\\n\"+str(e))\n logging.exception(\"FAILED! failed vars: \"+str(vars)+\"\\n\"+\"error:\")\n text_file = open(\"C:\\\\TEMP\\\\mplus\\\\errors.txt\", \"a\")\n text_file.write(\n \"failed vars: \"+str(vars)+\"\\n\"+\"error:\"+\"\\n\"+str(e))\n text_file.close()\n finally:\n t3 = datetime.now()\n took = (t3 - t2)/12\n print('it took :' + str(took))\n\n\nmain()\n","repo_name":"hadarbmdev/interactionAnalysis_thesis","sub_path":"runLca/mainDetedMothersOfLCAcat.py","file_name":"mainDetedMothersOfLCAcat.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13779979140","text":"import sys\r\ninput = lambda:sys.stdin.readline().strip()\r\n\r\nN = int(input())\r\nlst = [0]\r\nfor _ in range(N):\r\n lst.append(int(input()))\r\n\r\ndp = [0] * (N+1)\r\ndp[1] = lst[1]\r\n\r\nfor i in range(2,N+1):\r\n dp[i] = max(lst[i]+dp[i-2],lst[i]+lst[i-1] + dp[i-3])\r\n\r\nprint(dp[N])\r\n","repo_name":"Choihyoungkyu/algorithm","sub_path":"백준/Silver/2579. 계단 오르기/계단 오르기.py","file_name":"계단 오르기.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"5794030967","text":"class Node:\n def __init__(self, item):\n self.val = item\n self.left = None\n self.right = None\n\n\ndef Preorder(root):\n \"\"\" traverse root-left-right\"\"\"\n if root:\n \"traverse root\"\n print(str(root.val) + \"->\", end=\"\")\n \"traverse left\"\n Preorder(root.left)\n \"traverse right\"\n Preorder(root.right)\n\n\ndef Preorder_2(root):\n \"\"\" Tree traversal without recursion\"\"\"\n stack = [root]\n\n while len(stack) > 0:\n\n current = stack.pop()\n\n while current is not None:\n\n if current.right is not None:\n stack.append(current.right)\n\n print(current.val, end=\"->\")\n current = current.left\n\n\nif __name__ == \"__main__\":\n one = Node(1)\n two = Node(2)\n three = Node(3)\n four = Node(4)\n five = Node(5)\n six = Node(6)\n seven = Node(7)\n eight = Node(8)\n nine = Node(9)\n ten = Node(10)\n eleven = Node(11)\n twelve = Node(12)\n\n one.left = two\n one.right = three\n\n two.left = four\n two.right = five\n\n four.left = six\n four.right = seven\n\n five.left = eight\n\n three.left = nine\n three.right = ten\n\n nine.left = eleven\n ten.left = twelve\n\n print(\"Pre Oder Traversal \")\n Preorder(one)\n print()\n Preorder_2(one)\n\n","repo_name":"vabsalack/COMPETITIVE-CODING","sub_path":"Data Structures/Tree/Tree_Traversal/Pre_order_traversal.py","file_name":"Pre_order_traversal.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"70518901078","text":"#!/usr/bin/env python3\n\"\"\"\nPerforms Bayesian optimization on a noiseless 1D Gaussian process\n\"\"\"\nimport numpy as np\nGP = __import__('2-gp').GaussianProcess\n\n\nclass BayesianOptimization:\n \"\"\"\n A class that performs Bayesian optimization on a Gaussian process\n \"\"\"\n\n def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1,\n xsi=0.01, minimize=True):\n \"\"\"\n A function that initializes the class BayesianOptimization\n :param f: the black-box function to be optimized\n :param X_init: numpy.ndarray of shape (t, 1) representing the inputs\n already sampled with the black-box function\n :param Y_init: numpy.ndarray of shape (t, 1) representing the outputs\n of the black-box function for each input in X_init\n :param bounds: tuple of (min, max) representing the bounds of the\n space in which to look for the optimal point\n :param ac_samples: number of samples that should be analyzed during\n acquisition\n :param l: length parameter for the kernel\n :param sigma_f: standard deviation given to the output of the\n black-box function\n :param xsi: exploration-exploitation factor for acquisition\n :param minimize: bool determining whether optimization should be\n performed for minimization (True) or maximization (False)\n \"\"\"\n self.f = f\n self.gp = GP(X_init, Y_init, l, sigma_f)\n min, max = bounds\n self.X_s = np.linspace(min, max, ac_samples).reshape(-1, 1)\n self.xsi = xsi\n self.minimize = minimize\n","repo_name":"Kenneth-ca/holbertonschool-machine_learning","sub_path":"unsupervised_learning/0x03-hyperparameter_tuning/3-bayes_opt.py","file_name":"3-bayes_opt.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"85"} +{"seq_id":"41707459701","text":"\"\"\"\nCreated on 12/12/2019\n@author: Sunny Raj\n\"\"\"\n\"\"\"\nProblem Statement:\nWrite a Python program to add leading zeroes to a string\n\"\"\"\nstr_str = 'Welcome'\nstr_list = str_str.split(' ')\nlis = []\nnum = int(input('Enter the number of zeros you want to add before the string '))\n#loop that converts the list of numbers to 0 and stores them in lis variable\nfor i in range(num):\n lis.append(str(i*0))\n#adding the zeros list and string list\nadd = lis + str_list\nwords = ' '.join(add)\nprint(words)","repo_name":"SunnyRaj94/Basic-Python-And-Data-Structures","sub_path":"Basic/38_leading_0_to_string.py","file_name":"38_leading_0_to_string.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34797245125","text":"from django.test import TestCase\n\nimport json\n\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\n\nfrom placeholderapi.models import BlogUser\nfrom placeholderapi.constants import API_USER\n\nfrom decouple import config\n\nclass BlogUserTestCase(TestCase):\n\n def test_create_user(self):\n client = APIClient()\n\n test_user_data = {\n \"name\": \"name\",\n \"username\": \"cmantillam\",\n \"email\": \"email@email.com\",\n \"address\": {},\n \"phone\": \"11111111\",\n \"website\": \"www.web.com\",\n \"company\": {}\n }\n\n service = config('HOSTING') + API_USER\n response = client.post(\n service, \n test_user_data,\n format='json'\n )\n\n result = json.loads(response.content)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertIn('name', result)\n self.assertIn('username', result)\n self.assertIn('email', result)\n self.assertIn('phone', result)\n\n if 'id' in result:\n del result['id']\n\n self.assertEqual(result, test_user_data)\n\n\n def test_get_user(self):\n\n client = APIClient()\n\n BlogUser.objects.create(\n name=\"name\",\n username=\"cmantillam\",\n email=\"email@email.com\",\n address={},\n phone=\"11111111\",\n website=\"www.web.com\",\n company={}\n )\n\n service = config('HOSTING') + API_USER\n response = client.get(service)\n \n result = json.loads(response.content)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(len(result), 1)\n\n\n def test_delete_user(self):\n\n client = APIClient()\n\n\n user = BlogUser.objects.create(\n name=\"name\",\n username=\"cmantillam\",\n email=\"email@email.com\",\n address={},\n phone=\"11111111\",\n website=\"www.web.com\",\n company={}\n )\n\n service = config('HOSTING') + API_USER + f'{user.id}/'\n response = client.delete(\n service, \n format='json'\n )\n\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n\n user_exists = BlogUser.objects.filter(pk=user.id)\n self.assertFalse(user_exists)\n","repo_name":"Jcmantillam/JSONPlaceholder","sub_path":"placeholderapi/tests/test_blog_users.py","file_name":"test_blog_users.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"4963808107","text":"import sys\r\nfrom collections import deque\r\ninput = lambda: sys.stdin.readline().rstrip()\r\nINF = 20000001\r\n\r\n# 1. Monotone Queue 테크닉을 이용한다. (= 최솟값)\r\n# 2. 최대값은 무조건 [x, x + (N - K) - 1]의 양끝의 차이다.\r\nif __name__ == '__main__':\r\n N, K = map(int, input().split())\r\n V = [*sorted(map(int, input().split()))]\r\n\r\n result = INF\r\n\r\n idx = 1\r\n queue = deque([])\r\n\r\n # 슬라이딩 윈도우\r\n for offset in range(K + 1):\r\n # 범위에 해당되지 않는 원소를 제거한다.\r\n if queue and queue[0] <= offset:\r\n queue.popleft()\r\n\r\n # 최솟값을 구성하는 (두) 원소를 모두 저장하는 것이 아니라, 최솟값의 대표가 되는 원소만 저장한다.\r\n for x in range(idx, offset + (N - K)):\r\n while queue and (V[x] - V[x - 1]) <= (V[queue[-1]] - V[queue[-1] - 1]):\r\n queue.pop()\r\n\r\n queue.append(x)\r\n\r\n idx = offset + (N - K)\r\n M, m = V[idx - 1] - V[offset], V[queue[0]] - V[queue[0] - 1]\r\n\r\n result = min(result, M + m)\r\n\r\n print(result)\r\n","repo_name":"cutehammond772/problem-solving","sub_path":"백준/Platinum/3988. 수 고르기/수 고르기.py","file_name":"수 고르기.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41574207766","text":"# Phone and email extractor\n'''\n1. Use pyperclip to copy and paste strings\n2. Create two regexes, one for matching phone numbers and one for email addresses\n3. Find all matches of both regexes\n4. Neatly format matched strings into a single string to paste\n5. Display a message if no matches were found\n'''\n\nimport pyperclip\nimport re\n\n# Create phone regex\nphoneRegex = re.compile(r'''((\\d{3}|\\(\\d{3}\\))?(\\s|-|\\.)?(\\d{3})(\\s|-|\\.)(\\d{4})(\\s*(ext|x|ext.)\\s*(\\d{2,5}))?)''',\n re.VERBOSE)\n# Create email regex\nemailRegex = re.compile(r'''([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\\.[a-zA-Z]{2,4}))''', re.VERBOSE)\n\n# Find matches in clipboard text\ntext = str(pyperclip.paste())\nmatches = []\n\nfor groups in phoneRegex.findall(text):\n phoneNum = '-'.join([groups[1], groups[3], groups[5]])\n if groups[8] != '':\n phoneNum += ' x' + groups[8]\n matches.append(phoneNum)\n\nfor groups in emailRegex.findall(text):\n matches.append(groups[0])\n\n# Copy results to clipboard\nif len(matches) > 0:\n pyperclip.copy('\\n'.join(matches))\n print('Copied to clipboard.')\n print('\\n'.join(matches))\nelse:\n print('No matches found.')\n","repo_name":"rachaelcole/Python_Projects","sub_path":"ATBSWP/phoneAndEmail.py","file_name":"phoneAndEmail.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"23691466983","text":"\nfrom copy import deepcopy\n\nm =0 ##number of constraints\nn =0 ##number of variable\nc =[] ##coefficient vector\ncn=[]\nb=[] ##RHS\nbn=[]\nA=[] ##matrix\nAn=[]\nB=[] ##base matrix\nB_inv=[]\nx=[]\nbasicSet=[]\nnonBasicSet=[]\nc_B=[]\n\n\n\ndef exchangeRows(M,firstRow,secondRow):\n temp=M[firstRow][:]\n M[firstRow][:]=M[secondRow][:]\n M[secondRow][:]=temp\n \ndef multiplyRow(M,nonZeroConstant,rowNumber):\n for i in range(len(M[rowNumber])):\n M[rowNumber][i]=M[rowNumber][i]*nonZeroConstant\n \ndef multiplyMatrix(M, c):\n for i in range(len(M)):\n multiplyRow(M, c, i)\n \ndef rowOperationRow(M,firstRow,secondRow,c):\n for i in range(len(M[firstRow])):\n M[firstRow][i]=M[firstRow][i]+M[secondRow][i]*c\n \ndef printArr(M):\n for i in range(len(M)):\n try:\n for j in range(len(M[i])):\n print(\"{:.2f}\".format(M[i][j]),end =\" \")\n print() \n except:\n print(\"{:.2f}\".format(M[i]),end =\" \") \n \n\ndef pivoting(M):\n n=len(M)\n for row in range(0,n):\n col=row\n k=[]\n if M[row][col]==0:\n for j in range(row+1,n):\n if M[j][col]!=0:\n exchangeRows(M, j, row)\n break\n if M[row][col] == 0:\n for j in range(row+1,n) :\n if M[row][j]!=0:\n col=j\n \n for i in range(row+1,n):\n if M[row][col]!=0:\n k.append(-1*M[i][col]/M[row][col])\n \n p=0\n for j in range(row+1,n):\n if len(k)!=0:\n rowOperationRow(M, j, row,k[p])\n p=p+1\n \ndef getInverse(M):\n if len(M)==1:\n CT=[]\n CT.append(1/M[0][0])\n return CT\n C=getCofactor(M)\n CT=getTranspose(C)\n multiplyMatrix(CT, 1/getDeterminant(M))\n return CT\n \ndef getDeterminant(A):\n determinant=0\n if len(A)==1:\n return A[0][0]\n if len(A)==2:\n determinant=(A[0][0]*A[1][1]-A[0][1]*A[1][0])\n return determinant\n temp=deepcopy(A)\n for i in range(len(A)):\n x=A[0][i]\n temp=deletingCol(i,A)\n temp=deletingRow(0,temp)\n determinant=determinant + x*((-1)**i)*getDeterminant(temp)\n return determinant\n\ndef getCofactor(M):\n C=deepcopy(M) \n for i in range(len(M)):\n for j in range(len(M[i])):\n temp=deletingCol(j, M)\n temp=deletingRow(i,temp)\n C[i][j]=getDeterminant(temp)*((-1)**(i+j))\n return C \n \ndef deletingCol(colNumber,M):\n temp=deepcopy(M)\n [i.pop(colNumber) for i in temp]\n return temp\n\ndef deletingRow(rowNumber,M):\n temp=[]\n for i in range(len(M)):\n if i!=rowNumber:\n temp.append(M[i])\n return temp \n \ndef getTranspose(A):\n M=deepcopy(A);\n temp1=[]\n temp2=[]\n for colNumber in range(len(M[0])):\n temp1=[]\n [temp1.append(i.pop(0)) for i in M]\n temp2.append(temp1)\n return temp2\n\ndef getData(file):\n f=open(file)\n if (f.name.split(\".\")[1] == \"txt\"):\n global m,n,c,b,A,B,B_inv\n A=[]\n b=[]\n c=[]\n B=[]\n B_inv=[]\n print(file)\n line=f.readline()\n line=line.split(\"\\t\")\n line = list(map(int, line))\n m=int(line[0])\n n=int(line[1])\n line=f.readline()\n line=line.split(\"\\t\")\n c = list(map(float, line))\n for line in f:\n line=line.split(\"\\t\")\n line = list(map(float, line))\n b.append(line.pop(len(line)-1))\n A.append(line)\n return 1;\n return -1\n \ndef setB():\n global B,c_B,c,basicSet\n temp1=[]\n temp=deepcopy(A)\n B=[]\n c_B=[]\n for i in temp:\n for j in basicSet:\n temp1.append(i[j])\n B.append(temp1)\n temp1=[]\n for i in basicSet:\n if i>=len(c):\n c_B.append(0) \n else:\n c_B.append(c[i])\n\ndef addSlack(M):\n global m\n for i in range(m):\n for j in range(m):\n if(j==i):\n M[i].append(1)\n else:\n M[i].append(0)\n \ndef pricingOut():\n global cn,n\n cn=[]\n result=[]\n a=cbB()\n for i in range(len(A[0])):\n tot=0\n for j in range(len(a)):\n tot=tot+A[j][i]*a[j]\n result.append(tot)\n for j in nonBasicSet:\n if(j>=n):\n cn.append(-result[j])\n else:\n cn.append(c[j]-result[j])\n if(min(cn)>=0):\n return -1\n return cn.index(min(cn))\n\ndef RHS():\n global B_inv,bn,b\n bn=[]\n for i in range(len(b)):\n tot=0\n for j in range(len(b)):\n tot=tot+B_inv[i][j]*b[j]\n bn.append(tot)\n \ndef colX(colNumber):\n global B_inv,A,x\n x=[]\n temp=deepcopy(A)\n temp1=[]\n for i in temp:\n temp1.append(i.pop(colNumber))\n for i in range(m):\n tot=0\n for j in range(m):\n tot=tot+B_inv[i][j]*temp1[j]\n x.append(tot)\n\ndef setProblem():\n global m,n,c,b,A,B,c_B,basicSet,nonBasicSet\n addSlack(A)\n basicSet=[]\n nonBasicSet=[]\n for i in range(n):\n nonBasicSet.append(i)\n for i in range(n,m+n):\n basicSet.append(i)\n setB()\n \ndef cbB():\n global B,c_B,B_inv\n cbB=[]\n B_inv=getInverse(B)\n for i in range(len(B)):\n tot=0\n for j in range(len(c_B)):\n tot=tot+c_B[j]*B_inv[j][i]\n cbB.append(tot)\n return cbB \n\ndef ratioTest(colNumber):\n RHS()\n colX(colNumber)\n temp=[]\n for i in range(len(bn)):\n if(x[i]==0):\n temp.append(1000000)\n elif((bn[i]/x[i])>0):\n temp.append(bn[i]/x[i])\n else:\n temp.append(1000000)\n if min(temp)!=1000000 :\n return temp.index(min(temp))\n return -1\n\ndef minV():\n tot=0\n for i in range(len(b)):\n tot+=cbB()[i]*b[i]\n solution=[0]*(n+m)\n RHS()\n for i in range(len(basicSet)):\n solution[basicSet[i]]=bn[i]\n print(\"Optimal variable vector:\")\n print('[',end=''),printArr(solution),print(']') \n print(\"Optimal result: \")\n for i in range(m):\n c.append(0)\n print(tot,\"=\",c,\"*\",'[',end=(' ')),printArr(solution),print(']')\n return tot\n\ndef solveLP():\n global basicSet,nonBasicSet\n index_in=pricingOut()\n if index_in<0:\n return\n index_out=ratioTest(nonBasicSet[index_in])\n if index_out<0:\n return\n go_in=nonBasicSet[index_in]\n go_out=basicSet[index_out]\n basicSet[index_out]=go_in\n nonBasicSet[index_in]=go_out\n setB()\n solveLP()\n return\n \nimport os\nentries=os.listdir(os.getcwd())\nfor i in entries:\n if getData(i) >0:\n setProblem()\n solveLP()\n for i in cn:\n if (i<0):\n print(\"not optimal\")\n break\n if(i>=0):\n minV()\n\n","repo_name":"hamzaakyildiz/Linear-optimization","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":6912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9085547157","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom statistics import mode\nimport re\nfrom xgboost import XGBClassifier\n\n\n# In[2]:\n\n\nfile_path='./datas/'\nfile_name=file_path+\"h1b_dev_preprocessing.csv\"\ndf=pd.read_csv(file_name,keep_default_na=False)\ndf.columns\n\n\n# In[3]:\n\n\ndf[df.STATE.isna()]\n\n\n# In[4]:\n\n\ndf\n\n\n# In[5]:\n\n\ndf[['CASE_STATUS', 'FULL_TIME_POSITION', 'YEAR','SOC_CODE', 'STATE']]=df[['CASE_STATUS', 'FULL_TIME_POSITION', 'YEAR','SOC_CODE', 'STATE']].apply(lambda x : x.astype('category'))\n\n\n# In[8]:\n\n\nX = df.drop('CASE_STATUS', axis=1)\ny = df.CASE_STATUS\nseed = 6\ntest_size = 0.40\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=seed)\nX_train.columns\n\n\n# In[9]:\n\n\nX_train_encode = pd.get_dummies(X_train)\nX_test_encode = pd.get_dummies(X_test)\n\n\n# In[10]:\n\n\ntrain_X = X_train_encode.as_matrix()\ntrain_y = y_train.as_matrix()\n\n\n# In[11]:\n\n\ngbm=XGBClassifier(max_features='sqrt', subsample=0.8, random_state=10)\n\n\n# In[12]:\n\n\nfrom sklearn.model_selection import GridSearchCV\n\n\n# In[13]:\n\n\nparameters = [{'n_estimators': [10, 100]},\n {'learning_rate': [0.1, 0.01, 0.5]}]\n\n\n# In[14]:\n\n\ngrid_search = GridSearchCV(estimator = gbm, param_grid = parameters, scoring='accuracy', cv = 3, n_jobs=-1)\n\n\n# In[15]:\n\n\ngrid_search = grid_search.fit(train_X, train_y)\n\n\n# In[16]:\n\n\ngrid_search.grid_scores_, grid_search.best_params_, grid_search.best_score_\n\n\n# In[17]:\n\n\ngrid_search.best_estimator_\n\n\n# In[18]:\n\n\ngbm=XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n colsample_bytree=1, gamma=0, learning_rate=0.5, max_delta_step=0,\n max_depth=3, max_features='sqrt', min_child_weight=1, missing=None,\n n_estimators=100, n_jobs=1, nthread=None,\n objective='binary:logistic', random_state=10, reg_alpha=0,\n reg_lambda=1, scale_pos_weight=1, seed=None, silent=True,\n subsample=0.8).fit(train_X, train_y)\n\n\n# In[19]:\n\n\ny_pred = gbm.predict(X_test_encode.as_matrix())\n\n\n# In[20]:\n\n\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n\n","repo_name":"Ryulth/H1B_Visa_prediction_kaggle","sub_path":"python/model_XGB.py","file_name":"model_XGB.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"26044143747","text":"import webbrowser\nimport pyautogui\nfrom time import sleep\n\ndef send(text, phone):\n webbrowser.open(\"whatsapp://send?text=\" + text.replace('\\n', '%0A') + \"&phone=\" + phone.replace('+', ''))\n sleep(10)\n pyautogui.click(x=1787, y=978)\n sleep(0.2)\n pyautogui.hotkey('enter')\n sleep(1)\n # pyautogui.hotkey('alt', \"f4\")\n\nsend(\"Helo sir aag lag gaya ghar mein shayad iss baar mssg aa jaiga\", \"+918007953379\",)\n","repo_name":"RevTpark/smart_home_solutions","sub_path":"ardunio_whatsapp.py","file_name":"ardunio_whatsapp.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"10011359172","text":"from rest_framework.serializers import *\nfrom .models import *\n\n\n\nclass UserActivitySerializer(ModelSerializer):\n class Meta:\n model = ActivityPeriod\n fields = [\"start_time\",\"end_time\"]\n\nclass UserSerializer(ModelSerializer):\n activity = UserActivitySerializer(many=True)\n class Meta:\n model = User\n fields = [\"id\",\"real_name\",\"tz\",\"activity\"]\n\n def to_representation(self, instance):\n identifiers = dict()\n activity_obj = ActivityPeriod.objects.filter(activity_periods=instance.id).values(\"start_time\",\"end_time\")\n identifiers['id'] = instance.id\n identifiers['real_name'] = instance.real_name\n identifiers['tz'] = instance.tz\n identifiers['activity_periods'] = activity_obj\n representation = {\n 'members':[ identifiers,]\n }\n\n return representation","repo_name":"dineshbhupathi/fullthrottle_labs_task","sub_path":"fullthrottlelabs/usermanagement/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"28539922977","text":"\"\"\"\nFilename:hashset.py\n\nA set implementation based on hash function\n\"\"\"\n\nfrom LinkedBag.linked_structure import Node\nfrom ArrayBag.arrays import Array\nfrom Set.AbstractSet import AbstractSet\nfrom AbstractCollection import AbstractCollection\n\nclass HashSet(AbstractCollection,AbstractSet):\n \"\"\"A hashing implementation of a set.\"\"\"\n\n DEFAULT_CAPACITY=3\n def __init__(self,sourceCollection=None,capacity=None):\n\n if capacity==None:\n self._capacity=HashSet.DEFAULT_CAPACITY\n else:\n self._capacity=capacity\n self._item=Array(self._capacity)\n self._foundNode=self._priorNode=None\n self._index=-1\n AbstractCollection.__init__(self,sourceCollection)\n\n # Accessor methods\n def __contains__(self, item):\n \"\"\"Returns True if item is in the set or\n False otherwise.\"\"\"\n self._index=abs(hash(item))%len(self._item)\n self._priorNode=None\n self._foundNode=self._item[self._index]\n while self._foundNode!=None:\n if self._foundNode.data==item:\n return True\n else:\n self._priorNode=self._foundNode\n self._foundNode=self._foundNode.next\n return False\n\n def __iter__(self):\n \"\"\"Supports iteration over a view of self.\"\"\"\n if self.isEmpty():\n raise KeyError(\"The set is empty.\")\n\n else:\n for index in range(len(self._item)):\n self._priorNode=None\n self._foundNode=self._item[index]\n while self._foundNode!=None:\n yield self._foundNode.data\n self._priorNode=self._foundNode\n self._foundNode=self._foundNode.next\n\n def __str__(self):\n \"\"\"Returns the string representation of self.\"\"\"\n if self.isEmpty():\n return None\n else:\n for index in range(len(self._item)):\n list = []\n self._priorNode=None\n self._foundNode=self._item[index]\n while self._foundNode!=None:\n list.append(self._foundNode.data)\n self._priorNode=self._foundNode\n self._foundNode=self._foundNode.next\n print(str(index)+\":\"+\"-->\".join(map(str,list)))\n return \"string of set is shown above\"\n\n #Mutator methods\n def clear(self):\n \"\"\"Makes self become empty.\"\"\"\n self._size=0\n self._item=Array(HashSet.DEFAULT_CAPACITY)\n\n def add(self,item):\n \"\"\"Adds item to the set if it is not in the set.\"\"\"\n if not item in self:\n newNode=Node(item,self._item[self._index])\n self._item[self._index]=newNode\n self._size+=1\n\n def remove(self,item):\n \"\"\"Precondition: item is in self.\n Raises: KeyError if item is not in self.\n Postcondition: item is removed from self.\"\"\"\n if not item in self:\n raise KeyError(str(item)+\"is not in the set.\")\n else:\n if self._priorNode==None:\n self._item[self._index]=None\n else:\n self._priorNode.next=self._foundNode.next\n self._size-=1\n return str(item)+\"has been removed from the set.\"\n\n\n\n\n\n","repo_name":"JiangRIVERS/data_structure","sub_path":"Hash/hashset.py","file_name":"hashset.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34352184532","text":"from django.shortcuts import render, get_object_or_404\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import CreateView\nfrom django.http import HttpResponse\n\nfrom forum.models import Topic, Bucket\nfrom forum.forms import CommentForm, TopicForm\n\nimport os\nimport time\n\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\ndef handler404(request):\n response = render_to_response('404.html', {},\n context_instance=RequestContext(request))\n response.status_code = 404\n return response\n\ndef handler500(request):\n response = render_to_response('500.html', {},\n context_instance=RequestContext(request))\n response.status_code = 500\n return response\n\nt = time.localtime()\n\ntopics = Topic.objects.all()\ncontext = {'topics': topics,\n 'see_bucket':'see_bucket',\n 'topic_add_url':'add_topic',\n 'topic_sorted':'sorted',\n\t\t'hour':t.tm_hour+3,\n\t\t'minute':t.tm_min,\n\t\t'add_to_bucket':'bucket'}\n\ndef index(request):\n t = time.localtime()\n topics = Topic.objects.all()\n drinks = Topic.objects.filter(food_type=\"DR\")\n mains = Topic.objects.filter(food_type=\"MC\")\n salads = Topic.objects.filter(food_type=\"SD\")\n firsts = Topic.objects.filter(food_type=\"FC\")\n context = {\t'drinks': drinks,\n\t\t'firsts':firsts,\n\t\t'salads':salads,\n\t\t'mains':mains,\n 'see_bucket':'see_bucket',\n 'topic_add_url':'add_topic',\n 'topic_sorted':'sorted',\n\t\t'hour':t.tm_hour+3,\n\t\t'minute':t.tm_min,\n\t\t'add_to_bucket':'bucket'}\n return render(request, 'index.html', context)\n\ndef cleaning(request):\n meals = Bucket.objects.all().delete()\n \n return index(request)\n\ndef see(request):\n meals = Bucket.objects.all()\n allprice = int()\n allcall = int()\n for m in meals:\n my = str(m).split('|')\n allprice+=int(my[2])\n allcall+=int(my[1])\n\n context = {'meals': meals,\n 'allprice':allprice,\n 'allcall':allcall,\n\t\t'hour':t.tm_hour+3,\n\t\t'minute':t.tm_min}\n return render(request, 'see_bucket.html', context)\n\ndef bucket(request):\n\n for i in request.POST:\n arr = i.split('|')\n if len(arr)>2:\n b = Bucket(meal=str(arr[2]), price=int(arr[0]), calories=int(arr[1]))\n b.save()\n \n \n return index(request)\n\n\n\ndef sorted(request):\n\n topics = Topic.objects.all().order_by('-views')[:10]\n context = {'topics': topics,\n 'topic_add_url':'add_topic',\n 'topic_sorted':'sorted',\n 'name':os.getlogin(),\n\t\t'hour':t.tm_hour+3,\n\t\t'minute':t.tm_min}\n return render(request, 'index.html', context)\n\nclass TopicView(DetailView):\n model = Topic\n template_name = 'topic.html'\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if True:\n q1 = Topic.objects.get(pk=context['topic'].id)\n q1.views += 1\n q1.save()\n context['comment_add_url'] = \"/topic/{}/add_comment\".format(context['topic'].id)\n return context\n\nclass CommentAdd(CreateView):\n template_name = 'comment_add.html'\n form_class = CommentForm\n\n def get_initial(self):\n return {\n \"topic\": self.kwargs['topic_pk']\n }\n\n def get_success_url(self):\n return \"/topic/{}\".format(self.kwargs['topic_pk'])\n\n\nclass TopicAdd(CreateView):\n template_name = 'topic_add.html'\n form_class = TopicForm\n\n## def get_initial(self):\n## return {\n## \"topic\": self.kwargs['topic_pk']\n## }\n\n def get_success_url(self):\n return \"/\"#.format(self.kwargs['topic_pk'])\n\n\n\n","repo_name":"Serjio2888/BESTHack-Dining-Room","sub_path":"forum/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33336109666","text":"file = open(\"heyMr.txt\",\"r\")# Opens Target File\r\ndef compress(file):\r\n unique = []\r\n final = []\r\n for line in file:\r\n sentence = line.split()\r\n for word in sentence:\r\n if word not in unique:\r\n unique.append(word)\r\n for x in range(0,len(unique)):\r\n if word == unique[x]:\r\n final.append(x)\r\n print(final)\r\n print (unique)\r\n\r\n","repo_name":"CaptainCaveFish/Misc.","sub_path":"File_compressor.py","file_name":"File_compressor.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32019790536","text":"## Social Dynamics - 2 populations (infected/non-infected) / 2 opinions (attitudes / behaviors)\n## by Mike Phillips, 6/13/2018\n##\n## Exploring the drift coefficients and other properties appearing in the simple model.\n## The form of transition rates / drift coefficients comes from the Master / Fokker-Planck equations\n## Here we look at the case when the infected population is input as an explicit function of time.\n## The reason is that the infected fraction can remain nearly stationary when death processes are considered.\n## (If the base rate of infection is higher than that of curing, as expected since the rate of curing\n## can be nearly zero, then the stationary point for the infected fraction is close to unity, but\n## in reality new [uninfected] generations are born while older [infected] generations die quickly.)\n## Taking this case, we look for solutions of mean value equations for the remaining two variables:\n## x -> infection (fixed/controlled), y -> opinion (variable of interest), z -> 'belonging'\n##\n\n##import numpy as np\n##from scipy import optimize\n##import matplotlib.pyplot as plt\n\nfrom meanValueDefs import *\n\nPHASES = False # if you want to see (simple) phase curves: y,z vs. parameters\nDRIFTS = False # if you want to see plots of raw drifts: Ky, Kz vs. its own variable\nDRIFT3D = False # if you want 3D (surface/wireframe) plots of drifts\nFIXEDPTS = True # display fixed points / classification (from apx. nonlinear ODEs -> Jacobian)\nODESOL = True # if you want (apx.) solutions to system of ODEs\n\n\n# Initialize Time\ntmin = 0\nt = tmin\n# Initialize Fixed Point\n[y0,z0] = [0,0]\n# Initialize Initial Values\nyi, zi = 0.5, 0.5\n# Initialize Final / Threshold Values\ntmax = 20\nnmax = 120\n\nif PHASES:\n import phaseCurves\n [y0,z0] = phaseCurves.phasecurves(t)\n\n##if DRIFTS:\n## import driftPlots\n## driftPlots.driftplots(y0,z0,t)\n\nif FIXEDPTS:\n import symFP\n fpts = symFP.SYMFP(t, True) # second argument is for printing values/classificiations\n\nif DRIFT3D:\n import driftPlots3D\n driftPlots3D.drift3D(t)\n\nif ODESOL:\n import odeSol\n (tspace, ysol, zsol, fp) = odeSol.odesol(yi,zi,tmin,tmax,nmax)\n\nif DRIFTS and len(fp) > 0:\n import driftPlots\n driftPlots.driftplots(fp[0],fp[1],tmax)\n\n\n \n\n\n\n","repo_name":"mikeisahuman/socialHysteresis","sub_path":"src/meanValueMain.py","file_name":"meanValueMain.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"9312096267","text":"from django.conf import settings\nfrom django.core.mail import send_mail\n\nimport os\nimport sys\nsys.path.insert(0, './')\nimport django\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"myshop.settings\")\ndjango.setup()\n\nfrom c_tasks.celery import app as app\n\n# 定义任务函数\n@app.task\ndef send_register_active_email(to_email, username, token):\n \"\"\"发送激活邮件\"\"\"\n # 组织邮件内容\n subject = '电商平台欢迎你!'\n message = ''\n sender = settings.EMAIL_FROM\n receiver = [to_email]\n html_message = \"\"\"\n

    %s, 欢迎您注册会员

    \n 请点击以下链接激活您的账户(24个小时内有效)
    \n
    http://127.0.0.1:8001//active/?key=%s\n \"\"\" % (username, token, token)\n\n # 发送激活邮件\n # send_mail(subject=邮件标题, message=邮件正文,from_email=发件人, recipient_list=收件人列表)\n send_mail(subject, message, sender, receiver, html_message=html_message)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"yinglingxianghen/web","sub_path":"DianShang/apps/c_tasks/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"14704268612","text":"'''\nBy Paweł A. Pierzchlewicz\n=========================\nA library that has all the required functions for signal analysis\n=================================================================\n'''\n\n\n\n'''\n==========================\nImports\n==========================\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\nimport scipy.stats as st\nfrom scipy import signal\n\n\n'''\n==================\nMisc functions\n==================\n'''\ndef time(T=1, Fs=128):\n\treturn np.arange(0, T, 1/Fs)\n\ndef drawArray(A, columns=1, method=plt.plot, show=True):\n\tN = len(A)\n\tfor i, s in enumerate(A):\n\t\tplt.subplot(N,columns, i+1)\n\t\tmethod(s[0], s[1])\n\tif show: \n\t\tplt.show()\n\n'''\n==========================\nSignal Definition Functons\n==========================\n'''\n\n# Sin function\ndef sin(T = 1, f = 10, Fs = 128, phi = 0):\n\t'''\n\t\tT - Time length\n\t\tf - sin frequency\n\t\tFs - probing frequency\n\t\tphi - phase shift\n\t'''\n\t#Test for niquist frequency\n\tif f >= Fs/2:\n\t\traise Exception(\"[Aliasing imannet] {} Hz must be smaller than {} Hz\".format(f, Fs/2) )\n\tif Fs%128 != 0:\n\t\twarnings.warn(\"{} Hz is not the most optimal frequency for FFT\".format(Fs), Warning)\n\tt = time(T, Fs)\n\ts = np.sin(2*np.pi*f*t + phi)\n\treturn (t, s)\n\ndef white_noise(mu=0, std=1, T = 1, Fs = 128):\n\t'''\n\t\tWhite noise, a gaussian noise function\n\t\tmu - mean of gauss\n\t\tstd - standard deviation of gauss\n\t\tT - Time length\n\t\tFs - probing frequency\n\t'''\n\tt = time(T, Fs)\n\ts = st.norm.rvs(loc=mu, scale=std, size=T*Fs)\n\treturn (t, s)\n\ndef delta(t0, T = 1, Fs = 128, fit=True):\n\t'''\n\t\tA test function with one point at which it is equal 1\n\t\tt0 - point at which equal 1\n\t\tT - Time length\n\t\tFs - probing frequency\n\t'''\n\tt = time(T, Fs)\n\ts = np.zeros(T*Fs)\n\tif t0 > T:\n\t\traise Exception(\"t0 is {}s, but it cannot be larger than {}s\".format(t0, T))\n\tif not (np.where(t == t0)[0]) and not fit:\n\t\twarnings.warn(\"{} is not found in the time given, set fit=True to find the closest value to t0\".format(Fs), Warning)\n\tif not fit:\n\t\ts[s == t0] = 1\n\telse:\n\t\tsubtract = abs(t - t0)\n\t\tclosest = np.where(subtract == min(subtract))[0]\n\t\ts[closest] = 1\n\treturn (t, s)\n\n'''\n==================\nWindow functions\n==================\n'''\n\n# Module Constants\nsquare = 'square'\nhamming = 'hamming'\nhanning = 'hanning'\nblackman = 'blackman'\nbartlett = 'bartlett'\nhann = 'hann'\n\ndef window_signal(s, window):\n\treturn s*window\n\ndef window(type='square', N=128):\n\tif type == square:\n\t\treturn np.ones(N)\n\tif type == hamming:\n\t\treturn signal.hamming(N)\n\tif type == hanning:\n\t\treturn signal.hanning(N)\n\tif type == blackman:\n\t\treturn signal.blackman(N)\n\tif type == bartlett:\n\t\treturn signal.bartlett(N)\n\tif type == hann:\n\t\treturn signal.hann(N)\n\telse:\n\t\traise Exception('Unknown Window')\n\n\ndef filter(s, type=None, window_U=None):\n\tS = np.fft.rfft(s)\n\tif type:\n\t\tprint('here')\n\t\twindow_U = window(type, N = len(S))\n\tSo = window_signal(S, window_U)\n\tplt.plot(So)\n\tso = np.fft.irfft(So)\n\treturn(so)\n\ndef norm_window(window):\n\treturn np.linalg.norm(window)\n\n\n'''\n==================\nAnalysis functions\n==================\n'''\n\n\n# Widmo\ndef spectrum(s, t=None, Fs=128, draw = True):\n\t'''\n\t\ts - Signal\n\t\tFs - probing frequency\n\t\tdraw - whether to draw the graph or not\n\t'''\n\tS = abs(np.fft.rfft(s))**2\n\tS_freq = np.fft.rfftfreq(len(s), 1/Fs)\n\tif draw:\n\t\tdrawArray([(t,s), (S_freq, S)])\n\treturn(S_freq, S)\n\n\ndef multiply(s, T=1, N=1):\n\t'''\n\t\ts - signal\n\t\tN - number of times to multiply\n\t'''\n\ttN = time(T*N, len(s))\n\tsN = np.tile(s, N)\n\treturn (tN, sN)\n\ndef zero_padding(s, N=2, T=1):\n\tzeros = np.zeros(len(s)*(N-1))\n\ts0 = np.concatenate((s,zeros))\n\tt0 = time(T*N, len(t))\n\treturn (t0, s0)\n\n\ndef power(s, Fs=128, time=True):\n\tif time:\n\t\treturn s**2\n\telse:\n\t\t(S_freq, S) = spectrum(s=s, Fs=Fs, draw=False)\n\t\tP = S*S.conj()\n\t\tP /= Fs\n\t\tP = P.real\n\t\tif len(s)%2 == 0:\n\t\t\tP[1: -1] *= 2\n\t\telse:\n\t\t\tP[1:] *= 2\n\t\treturn (S_freq, P)\n\ndef energy(s, Fs, time=True):\n\tif time:\n\t\tP = power(s)\n\t\tdt = 1/Fs\n\t\treturn np.sum(power(s)*dt)\n\telse:\n\t\treturn np.sum(power(s, Fs, time=False))\n\ndef mean (s, Fs):\n\tN = len(s)\n\tw = window(N = s.shape[1])\n\tspectrums = np.zeros((N, int(s.shape[1]/2+1)))\n\tfor i, sig in enumerate(s):\n\t\twindow_signal(s, w)\n\t\t(F, P) = power(sig*w, Fs, time=False)\n\t\tspectrums[i] = P\n\tmean = np.mean(spectrums, axis=0)\n\ttrust_interval = np.zeros((len(F), 2)) # [[lower, higher], ...]\n\tfor f in enumerate(F):\n\t\tf_0 = f[0]\n\t\ttrust_interval[f_0] = [\n\t\t\tst.scoreatpercentile(spectrums[:, f_0], 2.5),\n\t\t\tst.scoreatpercentile(spectrums[:, f_0], 97.5)\n\t\t]\n\treturn (F, mean, trust_interval)\n\n'''\n==================\nTesting functions\n==================\n'''\n\nif __name__ == '__main__':\n\tN = 20 # liczba realizacji\n\tT = 1 # 1 s\n\tFs = 100 # Hz\n\tf = 20 # Hz\n\trealizacje = np.zeros((N, T*Fs)) # tablica na realizacje\n\tfor i in range(N):\n\t (t, s) = sin(f=20,T=1, Fs =100) #realizacja sinusa\n\t (t, sz) = white_noise(T=1, Fs=100)#realizacja szumu\n\t syg = s+sz # sygnał będący sumą powyższych\n\t realizacje[i,:] = syg # wkładamy go do tablicy\n\t(F, mean, trust_interval) = mean(realizacje, Fs)\n\tplt.plot(F, mean, 'r')\n\tplt.plot(F, trust_interval[:, 0], 'b--')\n\tplt.plot(F, trust_interval[:, 1], 'b--')\n\tplt.show()\n","repo_name":"PPierzc/Signal-Analysis","sub_path":"as.py","file_name":"as.py","file_ext":"py","file_size_in_byte":5151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13932639250","text":"# _*_ coding:utf-8 _*_\n# 把数组翻译成字符串\n\n\n# 本题主要是动态规划的算法\n# 注意状态转移\n\nclass Solution:\n def transnum(self, numbers):\n num = str(numbers)\n \n dp = [1 for i in range(len(num)+1)]\n for i in range(2,len(dp)):\n dp[i] = dp[i-1]\n temp = int(num[i-2:i])\n print(temp)\n if temp >= 10 and temp <= 25:\n dp[i] += dp[i-2]\n return dp[-1]\n\n\nso = Solution()\nprint(so.transnum(10))","repo_name":"TernenceWind/jianzhiOffer","sub_path":"chapter 5/46_transnumtostr.py","file_name":"46_transnumtostr.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"28696413804","text":"#!/usr/bin/env python3\n\nfrom trec_car.read_data import *\nimport argparse\n\ndef dump_pages(args):\n for p in iter_pages(args.file):\n print(p.page_meta)\n print(p)\n print(\"\\n\".join([(\"%s %s\"% (heading,content)) for (heading,content) in p.deep_headings_list()]))\n\ndef dump_outlines(args):\n for p in iter_outlines(args.file):\n print(p.page_meta)\n print(p)\n print(\"\\n\".join([(\"%s\"% heading ) for (heading,empty_content) in p.deep_headings_list()]))\n\ndef dump_paragraphs(args):\n for p in iter_paragraphs(args.file):\n print(p)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n subparser = parser.add_subparsers()\n p = subparser.add_parser('pages', help='Dump pages')\n p.add_argument('file', type=argparse.FileType('rb'), help='A pages file')\n p.set_defaults(func=dump_pages)\n\n p = subparser.add_parser('outlines', help='Dump outlines')\n p.add_argument('file', type=argparse.FileType('rb'), help='An outlines file')\n p.set_defaults(func=dump_outlines)\n\n p = subparser.add_parser('paragraphs', help='Dump paragraphs')\n p.add_argument('file', type=argparse.FileType('rb'), help='A paragraphs file')\n p.set_defaults(func=dump_paragraphs)\n\n args = parser.parse_args()\n if 'func' not in args:\n parser.print_usage()\n else:\n args.func(args)\n","repo_name":"huggingface/datasets-server","sub_path":"services/worker/vendors/trec-car-tools/python3/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":549,"dataset":"github-code","pt":"85"} +{"seq_id":"35841852828","text":"\"\"\"\nThis module is for the Raspberry Pi System\nIt Retrieves System & Sensor data\n\nTested on the RP3B+ & RPWZ\n\nCreated on Sat Aug 25 08:53:56 2018\n\n@author: OO-Dragon\n\"\"\"\nimport os\nimport time\nfrom operations_modules import logger\nfrom configuration_modules import app_config_access\n\nround_decimal_to = 5\npause_sensor_during_access_sec = 0.005\n\n\nclass CreateRPSystem:\n \"\"\" Creates Function access to Raspberry Pi Hardware Information. \"\"\"\n\n def __init__(self):\n self.sensor_in_use = False\n try:\n self.gp_import = __import__(\"gpiozero\")\n self.enable_raspberry_pi_hardware()\n logger.sensors_logger.debug(\"Raspberry Pi System Access Initialization - OK\")\n except Exception as error:\n logger.sensors_logger.error(\"Raspberry Pi System Access Initialization - Failed: \" + str(error))\n app_config_access.installed_sensors.raspberry_pi = 0\n app_config_access.installed_sensors.update_configuration_settings_list()\n\n def cpu_temperature(self):\n \"\"\" Returns System CPU Temperature as a Float. \"\"\"\n while self.sensor_in_use:\n time.sleep(pause_sensor_during_access_sec)\n self.sensor_in_use = True\n try:\n cpu = self.gp_import.CPUTemperature()\n cpu_temp_c = float(cpu.temperature)\n except Exception as error:\n cpu_temp_c = 0.0\n logger.sensors_logger.error(\"Raspberry Pi CPU Temperature Sensor - Failed: \" + str(error))\n self.sensor_in_use = False\n return round(cpu_temp_c, round_decimal_to)\n\n @staticmethod\n def enable_raspberry_pi_hardware():\n \"\"\" Enables I2C, SPI & Wireless on Raspberry Pis. \"\"\"\n try:\n os.system(\"raspi-config nonint do_i2c 0\")\n os.system(\"raspi-config nonint do_spi 0\")\n os.system(\"rfkill unblock 0\")\n except Exception as error:\n logger.sensors_logger.error(\"Error enabling Raspberry Pi I2C, SPI & Wifi: \" + str(error))\n","repo_name":"chad-ermacora/kootnet-sensors","sub_path":"sensor_modules/raspberry_pi_system.py","file_name":"raspberry_pi_system.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"24661031749","text":"#extrator de números de telefone e de endereços de email\n#padrões aceitaveis de telefones: 0800 729 0721/ (22) 324 43567\n\nimport pyperclip, re\n\n\n#regex para telefone\nfoneRegex = re.compile(r'''(\n(\\d{2,4}|\\(\\d{2}\\))? # código de área\n(\\s|-|\\.)+ # separador\n(\\d{3}) # primeiros 3 dígitos /////\n(\\s|-|\\.) # separador /////\n(\\d{2,}) # últimos 4 dígitos\n(\\s*(ext|x|ext.)\\s*(\\d{2,5}))? # extensão\n)''', re.VERBOSE)\n\n\n#regex para endereço de email\nemailRegex = re.compile(r'''(\n [a-zA-Z0-9._%+-]+ # nome do usuário\n @ # símbolo @\n [a-zA-Z0-9.-]+ # nome do domínio\n(\\.[a-zA-Z]{2,4}) # ponto seguido de outros caracteres\n)''', re.VERBOSE)\n\n#Encontra as correspodências no texto do clipboard\ntexto = str(pyperclip.paste())\nlista = []\nfor grupos in foneRegex.findall(texto):\n foneNum = '-'.join([grupos[1], grupos[3], grupos[5]])\n if grupos[8] != '':\n foneNum += ' x' + grupos[8]\n lista.append(foneNum)\nfor grupos in emailRegex.findall(texto):\n lista.append(grupos[0])\n\n# Copia os resultados para o clipboard.\nif len(lista) > 0:\n pyperclip.copy('\\n'.join(lista))\n print('Copiado para o clipboard:')\n print('\\n'.join(lista))\nelse:\n print('Não foram detectados números ou emails')","repo_name":"gitjonatan/Python","sub_path":"RegexClipboard/projetoPhoneAndEmail.py","file_name":"projetoPhoneAndEmail.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"24499123336","text":"def pascalsTri(n):\n \"\"\"Row 1 is considered 1 1, row 2 is 1 2 1\"\"\"\n triangle = [[1, 1]]\n\n for currentRow in range(2, n + 1):\n lastRow = triangle[len(triangle) - 1]\n nextRow = [0]\n for number in lastRow:\n nextRow[len(nextRow) - 1] += number\n nextRow.append(number)\n triangle.append(nextRow)\n return triangle\n\nsums = 0\nfor x in pascalsTri(20)[19]:\n sums += x ** 2\nprint(sums)\n","repo_name":"conor-mcavoy/euler","sub_path":"015.py","file_name":"015.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33739983500","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 19 16:27:05 2018\n\n@author: arnik\n\"\"\"\n\"\"\"\nCreate a function called repeatify that takes in two arguments as the input - a string and a number. \nThe function should return the string repeated the given numberof times. \nIf the first argument is not a string or the second argument is not a number, \nreturn false.\n\nExample: repeatify('hello',3) should return 'hellohellohello'.\n\"\"\"\ndef repeatify(s,num):\n if(type(s)!= str or type(num) != int):\n return False\n \n \n list1= list(s)\n result= list1 * num\n result1= \"\".join(result)\n return result1\n\n\nprint(repeatify(\"hello\", 3));\n \n \n \n \n","repo_name":"arnika13/Programming_Challenges","sub_path":"Python_Programs/repeatify_WWC.py","file_name":"repeatify_WWC.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19536180941","text":"import torch\nimport triton\nimport triton.language as tl\n\n@triton.jit\ndef add_kernel(\nx_ptr, # pointer to the first input vector \ny_ptr, # Pointer to the second input vector\noutput_ptr, # Pointer to the output vetor\nn_elements, # Size of the vector\n**meta, # Optional meta parameters for the kernel\n ):\n BLOCK_SIZE = meta['BLOCK_SIZE'] # how many input each program should process\n # There are multiple 'program's processing different data. We identify which \n # program.\n pid = tl.program_id(axis=0) # We use a 1D launch grid so axis is 0\n # This program will process inputs that are offset from the initial data.\n # For instance, if you had a vector of length 256 and block_size of 64, the \n # programs would each access the elements [0:64, 64:128, 128:196, 196: 256].\n # Note that offsets is a list of pointers.\n block_start = pid * BLOCK_SIZE\n offsets = block_start + tl.arange(0, BLOCK_SIZE)\n # Create a mask to guard memory against out-of-bounds accesses\n mask = offsets < n_elements\n # Load x and y from DRAM, masking out any extra elements in case the input\n # is not a multiple of the block size\n x = tl.load(x_ptr + offsets, mask=mask)\n y = tl.load(y_ptr + offsets, mask=mask)\n output = x + y\n # Write x + y back to DRAM\n tl.store(output_ptr + offsets, output, mask=mask)\n","repo_name":"aiwizzard/learning-triton","sub_path":"vector_addition/vector_addition.py","file_name":"vector_addition.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34130531149","text":"# Menu - OK\n# Método Sleep ou Clear - +-\n# Cor - OK\n# Saldo - +-\n# Funcionalidade Extra - FALTA\n# READ.me - FALTA\n\n\n# ***********************LEMBRAR DE MUDAR OS PATHS\n# CADA TRANSAÇÃO É UM DICIONARIO, DENTRO DE UMA LISTA DE TRASACOES\nplanilha = [{\"nome\": \"Nome\", \"categoria\": \"Categoria\", \"valor\": \"Valor\"}]\n# NOVA TRANSACAO (EX)\ntransacao = {}\n\nimport os\n\n\ndef clear_screen():\n os.system(\"cls\" if os.name == \"nt\" else \"clear\")\n\n\n#######################funcao read\ndef ler():\n global planilha\n try:\n with open(\n \"/Users/brunoribeiro/Documents/GitHub/projetoFP/transacoes.csv\", \"r\"\n ) as file:\n linhas = file.readlines() # TODAS AS LINHAS VIRAM UM ITEM DE UMA LISTA\n for linha in linhas[1:]: # ???? 1 NAO PEGA O \"TITULO\" DO ARQUIVO\n itens = linha.strip().split(\n \",\"\n ) # ITENS = LISTA QUE TEM OS DADOS DE CADA TRANSAÇÃO\n transacao = {\n \"nome\": itens[0],\n \"categoria\": itens[1],\n \"valor\": float(itens[2]),\n } # PEGA CADA TRANSACAO E ADICIONA NO DICIONARIO\n planilha.append(transacao)\n except FileNotFoundError:\n pass # PESQUISAR SOBRE (BREAK SO FUNCIONA DENTRO DO WHILE, COMO É UMA FUNCAO QUE VAI SER CHAMADA NAS OUTRAS, NAO PRECISA DO WHILE)\n\n return planilha\n\n\n##############################funcao write\ndef armazena(): # TRANSFORMAR O DICIONARIO TRANSACAO EM UM STRING LINHA\n with open(\n \"/Users/brunoribeiro/Documents/GitHub/projetoFP/transacoes.csv\",\n \"w+\",\n encoding=\"utf-8\",\n ) as file:\n for i, transacao in enumerate(planilha): # i é idice, nao usei\n itens = []\n for dados in transacao.values():\n itens.append(str(dados))\n linha = \",\".join(itens)\n file.write(linha + \"\\n\")\n\n\n#############################funcao add\ndef adicao():\n print(\"Adicionando nova transação:\")\n with open(\n \"/Users/brunoribeiro/Documents/GitHub/projetoFP/transacoes.csv\", \"w\"\n ) as file:\n nome = str(input(\"Nome: \"))\n categoria = str(input(\"Categoria: \")).title()\n valor = str(input(\"Valor: R$\"))\n transacao = {\"nome\": nome, \"categoria\": categoria, \"valor\": valor}\n planilha.append(transacao)\n armazena()\n\n\n#############################funcao delete\ndef delete():\n print(\"Apagando uma transação existente: \")\n with open(\n \"/Users/brunoribeiro/Documents/GitHub/projetoFP/transacoes.csv\", \"r\"\n ) as file:\n nome = str(input(\"Nome: \"))\n categoria = str(input(\"Categoria: \")).title()\n valor = float(input(\"Valor: R$\"))\n transacao_pra_achar = {\"nome\": nome, \"categoria\": categoria, \"valor\": valor}\n ler()\n planilha.remove(transacao_pra_achar)\n armazena()\n\n\n# USAR ISSO PARA O CÓDIGO FINAL\n\n\n# Função criada para calcular o saldo do usuário\ndef calculandoSaldo():\n saldo = 0\n for transacao in planilha:\n preco = transacao.get(\"valor\") # ???\n if preco:\n saldo += float(preco) # ??????\n\n # Verificando se o saldo é positivo ou negativo (maior ou menor que zero), e dependendo se ele for positivo ou negativo irá retornar uma cor diferente\n if saldo >= 0:\n saldoFinal = \"\\033[92mR${:.2f}\\033[0m\".format(saldo) # Verde\n else:\n saldoFinal = \"\\033[91mR${:.2f}\\033[0m\".format(saldo) # Vermelho\n\n return saldoFinal\n\n\n# Criação da funcionalidade que deleta tudo que tem no arquivo .csv\n\"\"\"\ndef apagaTudo():\n\"\"\"\n\n\n# Carregar as transações existentes\nplanilha = ler()\n# transactions = read_transactions() #TA ERRADO ler()\n\n\n# Criando um def para menu para não ficar muitas linhas de código no loop principal\ndef menu():\n print(\"\\033[0m\")\n\n print(\"\\033[1;3m--------------------------------\")\n print(\"\\033[1;3m MENU PRINCIPAL\")\n print(\"\\033[1;3m--------------------------------\")\n\n print(\"\\033[0;34m 1. Adicionar Transação\")\n print(\"\\033[0;35m 2. Listar Todas as Transações\")\n print(\"\\033[0;36m 3. Atualização de uma Transação\")\n print(\"\\033[0;37m 4. Apagar uma Transação\")\n print(\"\\033[0;33m 5. Apagar TODAS as Transações\")\n print(\"\\033[0;34m 6. Ver Saldo Atual\")\n print(\"\\033[0;31m 7. Sair do Programa\")\n print(\"\\033[0m\")\n\n\nwhile True:\n clear_screen()\n\n menu()\n\n acao = input(\"\\033[1m\\nEscolha uma opção: \")\n\n if acao == \"1\":\n # ler() Talvez não precise de nenhum desse ler() !!!!!!!!!!!!!!!!\n adicao()\n input(\"\\033[0;30m\\nPressione Enter para continuar...\")\n\n elif acao == \"4\":\n # ler() Talvez não precise de nenhum desse ler() !!!!!!!!!!!!!!!!\n delete()\n # list_all_transactions(transactions) VER SE PRECISA DISSO\n input(\"\\033[0;30m\\nPressione Enter para continuar...\")\n\n elif acao == \"6\":\n # ler() Talvez não precise de nenhum desse ler() !!!!!!!!!!!!!!!!\n print(f\"Saldo Atual: {calculandoSaldo()}\")\n input(\"\\033[0;30m\\nPressione Enter para continuar...\")\n\n elif acao == \"7\":\n print(\"\\033[1m\\nObrigado por utilizar o nosso Sistema de Controle Financeiro!\")\n break\n\n else:\n print(\"\\033[91mOpção inválida. Por favor, tente novamente.\")\n input(\"\\033[0;30m\\nPressione Enter para continuar...\")\n\n \"\"\"\n elif acao == \"2\":\n # ler() Talvez não precise de nenhum desse ler() !!!!!!!!!!!!!!!!\n extrato()\n # list_all_transactions(transactions) VER SE PRECISA DISSO\n input(\"\\033[0;30m\\nPressione Enter para continuar...\")\n\n \n elif acao == \"3\":\n # ler() Talvez não precise de nenhum desse ler() !!!!!!!!!!!!!!!!\n atualizacao()\n # list_all_transactions(transactions) VER SE PRECISA DISSO\n input(\"\\033[0;30m\\nPressione Enter para continuar...\")\n\n\n elif acao == \"5\":\n # ler() Talvez não precise de nenhum desse ler() !!!!!!!!!!!!!!!!\n zerar = input(\"\\nVocê tem CERTEZA que deseja apagar TUDO? [S] ou [N]\\n\")\n if zerar == \"S\" or zerar == \"s\":\n apagarTudo()\n elif zerar == \"N\" or zerar == \"n\":\n continue\n else:\n print(\"\\033[91mOpção inválida. Por favor, tente novamente.\")\n\n input(\"\\033[0;30m\\nPressione Enter para continuar...\")\n \"\"\"\n","repo_name":"brunoribeirol/projetoFP","sub_path":"Processo/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41797273322","text":"#!/usr/bin/env python\n# Simple function which uses smbus to interface with the Si7021-A20\n# digital temperature and humidity sensor\n# adapted from http://www.pibits.net/code/raspberry-pi-si7021-sensor-example.php\nimport smbus\nimport time\n\n# Simple function which uses smbus to query the Si7021-A20 digital sensor\n# This sensor has a default I2C address of 0x40.\ndef querySI(address=0x40):\n # Get I2C bus\n bus = smbus.SMBus(1)\n bus.write_byte(address, 0xF5)\n\n # Time delay\n time.sleep(0.3)\n \n # SI7021 address, 0x40 Read 2 bytes, Humidity\n data0 = bus.read_byte(address)\n data1 = bus.read_byte(address)\n\n # Convert the data using equation from section 5.1.1. of https://www.silabs.com/documents/public/data-sheets/Si7021-A20.pdf\n humidity = ((data0 * 256 + data1) * 125 / 65536.0) - 6\n \n time.sleep(0.3)\n bus.write_byte(address, 0xF3)\n time.sleep(0.3)\n \n # SI7021 address, 0x40 Read data 2 bytes, Temperature\n data0 = bus.read_byte(address)\n data1 = bus.read_byte(address)\n \n # Convert the data using euqation from section 5.1.2. of https://www.silabs.com/documents/public/data-sheets/Si7021-A20.pdf\n celsTemp = ((data0 * 256 + data1) * 175.72 / 65536.0) - 46.85\n fahrTemp = celsTemp * 1.8 + 32\n\n # Initialize the dictionary which will be returned\n sensorReading = {}\n sensorReading[\"Temp\"], sensorReading[\"RH\"] = celsTemp, humidity\n\n # print(f\"Relative Humidity is : {humidity} %\")\n # print(f\"Temperature in Celsius is : {celsTemp} C\")\n # print(f\"Temperature in Fahrenheit is : {fahrTemp}\")\n\n return sensorReading\n\n","repo_name":"tristanCB/si7021-a20-python","sub_path":"Si7021_A20.py","file_name":"Si7021_A20.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29681505180","text":"from src.io.CommandInterpreter import Command, Movement, TravelAction, \\\n CommandTypes\nfrom src.io.OutputBuilder import print_to_player, PrintArg, print_room_to_player\nfrom src.rooms.RoomCRUD import lookup_room, lookup_room_exits\nfrom src.rooms.RoomClasses import Direction, Coordinates\nfrom src.sqlitehelper import SQLiteHelper\n\n\ndef calc_coords_from_playerloc_and_dir(player):\n if player.store is None:\n player.coords.x = player.coords.y = player.coords.z = -1\n return\n\n info = Command()\n info.type = CommandTypes.COMMAND_NOT\n info.subtype = CommandTypes.COMMAND_NOT\n\n coords = Coordinates()\n coords.x += x_movement_to_vector(info)\n coords.y += y_movement_to_vector(info)\n coords.z += z_movement_to_vector(info)\n\n return coords\n\n\ndef x_movement_to_vector(info):\n if any(info.subtype in i for i in (Direction.DIR_EAST,\n Direction.DIR_NORTHEAST,\n Direction.DIR_SOUTHEAST)):\n return 1\n elif any(info.subtype in i for i in (Direction.DIR_SOUTHWEST,\n Direction.DIR_NORTHWEST,\n Direction.DIR_WEST)):\n return -1\n\n return 0\n\n\ndef y_movement_to_vector(info):\n if any(info.subtype in i for i in (Direction.DIR_NORTH,\n Direction.DIR_NORTHEAST,\n Direction.DIR_NORTHWEST)):\n return 1\n elif any(info.subtype in i for i in (Direction.DIR_SOUTHEAST,\n Direction.DIR_SOUTHWEST,\n Direction.DIR_SOUTH)):\n return -1\n\n return 0\n\n\ndef z_movement_to_vector(info):\n if info.subtype == Direction.DIR_UP:\n return 1\n elif info.subtype == Direction.DIR_DOWN:\n return -1\n\n return 0\n\n\ndef do_movement_cmd(player, info):\n direction = Movement.DIR_NOT\n origin = player.coords\n destination = {0}\n\n if info.subtype == Movement.DIR_NORTH:\n direction = Movement.DIR_NORTH\n destination.y = origin.y + 1\n elif info.subtype == Movement.DIR_EAST:\n direction = Movement.DIR_EAST\n destination.x = origin.x + 1\n elif info.subtype == Movement.DIR_SOUTH:\n direction = Movement.DIR_SOUTH\n destination.y = origin.y - 1\n elif info.subtype == Movement.DIR_WEST:\n direction = Movement.DIR_WEST\n destination.x = origin.x - 1\n elif info.subtype == Movement.DIR_DOWN:\n direction = Movement.DIR_DOWN\n destination.z = origin.z - 1\n elif info.subtype == Movement.DIR_UP:\n direction = Movement.DIR_UP\n destination.z = origin.z + 1\n elif info.subtype == Movement.DIR_NORTHWEST:\n direction = Movement.DIR_NORTHWEST\n destination.x = origin.x - 1\n destination.y = origin.y + 1\n elif info.subtype == Movement.DIR_NORTHEAST:\n direction = Movement.DIR_NORTHEAST\n destination.x = origin.x + 1\n destination.y = origin.y + 1\n elif info.subtype == Movement.DIR_SOUTHWEST:\n direction = Movement.DIR_SOUTHWEST\n destination.x = origin.x - 1\n destination.y = origin.y - 1\n elif info.subtype == Movement.DIR_SOUTHEAST:\n direction = Movement.DIR_SOUTHEAST\n destination.x = origin.x + 1\n destination.y = origin.y - 1\n\n dest_room = lookup_room(destination)\n if dest_room is None:\n print(\"oh no\")\n # do something\n\n rv = lookup_room_exits(origin, dest_room)\n\n if rv == -1:\n print_to_player(player, PrintArg.PRINT_INVAL_DIR)\n return\n elif rv == -2:\n # send them back to origin room, somewhere they shouldn't be\n destination.x = 0\n destination.y = 0\n destination.z = 0\n print_to_player(player, PrintArg.PRINT_INVAL_DIR)\n # check me\n else:\n print_to_player(player, direction)\n\n adjust_player_location(player, dest_room.id)\n print_room_to_player(player, dest_room)\n\n\ndef do_travel_cmd(player, info):\n if info.subtype == TravelAction.TRAVEL_GOTO:\n print(\"ADD ME %d\\n\", player.socket_num)\n\n if info.subtype == TravelAction.TRAVEL_SWAP:\n print(\"ADD ME %d\\n\", player.socket_num)\n\n\ndef adjust_player_location(player, room_id):\n return SQLiteHelper.SQLExecution(\n \"UPDATE PLAYERS SET loc_id =:room_id WHERE name =:pname\",\n {\"loc_id\": room_id, \"name\": player.name},\n SQLiteHelper.DBTypes.PLAYER_DB)\n\n\n","repo_name":"0xtr/minimud_python","sub_path":"src/players/PlayerMovement.py","file_name":"PlayerMovement.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73311006998","text":"import time\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\n# strip.numPixels()\n# strip.setPixelColor(120, Color(255, 0, 0)) RED GREEN BLUE\n# strip.setBrightness(255)\n# strip.show()\n\nLED_COUNT = 134 # Number of LED pixels.\nLED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).\nLED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)\nLED_DMA = 10 # DMA channel to use for generating signal (try 10)\nLED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest\nLED_INVERT = False # True to invert the signal (when using NPN transistor level shift)\nLED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53\nLED_STRIP = ws.WS2811_STRIP_GRB # Strip type and colour ordering\n\n\ndef colorWipe(strip, color, wait_ms=25):\n strip.setBrightness(brightness)\n turnOff(strip)\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, color)\n strip.show()\n time.sleep(wait_ms/1000.0)\n\n\ndef colorWipeReverse(strip, color, wait_ms=25):\n strip.setBrightness(brightness)\n turnOff(strip)\n for i in range(strip.numPixels()):\n strip.setPixelColor(LED_COUNT - i - 1, color)\n strip.show()\n time.sleep(wait_ms/1000.0)\n\n\ndef theaterChase(strip, color, wait_ms=50, iterations=10):\n \"\"\"Movie theater light style chaser animation.\"\"\"\n for j in range(iterations):\n for q in range(3):\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, color)\n strip.show()\n time.sleep(wait_ms/1000.0)\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, 0)\n\n\ndef theaterChaseTwoTone(strip, wait_ms=50, iterations=15):\n \"\"\"Movie theater light style chaser animation.\"\"\"\n for j in range(iterations):\n for q in range(2):\n for i in range(0, strip.numPixels(), 2):\n strip.setPixelColor(i+q, Color(0, 255, 0))\n strip.show()\n time.sleep(wait_ms/1000.0)\n for i in range(0, strip.numPixels(), 2):\n strip.setPixelColor(i+q, Color(255, 255, 0))\n\n\ndef allSameColor(strip, color):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, color)\n strip.show()\n\n\ndef turnOff(strip):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, Color(0, 0, 0))\n strip.show()\n\n\nif __name__ == '__main__':\n\n strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)\n strip.begin()\n\n allSameColor(strip, Color(0, 255, 0))\n\n while True:\n colorWipe(strip, Color(0, 255, 0))\n time.sleep(1)\n colorWipe(strip, Color(255, 255, 0))\n time.sleep(1)\n colorWipeReverse(strip, Color(0, 255, 0))\n time.sleep(1)\n colorWipeReverse(strip, Color(255, 255, 0))\n time.sleep(1)\n theaterChaseTwoTone(strip)\n time.sleep(1)\n","repo_name":"JonKiddy/RaspberryPi-NeoPixels-And-Networktables","sub_path":"OnPi.kermit.py","file_name":"OnPi.kermit.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"73545662359","text":"import os\nimport pickle\nfrom copy import deepcopy\nimport datetime\nimport numpy as np\nimport logging\n\n# Used for typehints\nfrom ..objects.auvsim import AUVSim\nfrom ..objects.shape import Shape\nfrom ..objects.sensor import Radar\nfrom typing import List, Type\n\nfrom .plotutils import EpisodeVisualization\n\n# Set logger\nlogger = logging.getLogger(__name__)\n\n\nclass FullDataStorage:\n \"\"\"\n Class to save general simulation data over all the runs/ episodes of simulation:\n - the info dictionary\n - cumulative rewards array\n\n Pass the created environment by reference and update the Full Data Storage at the end of each episode\n \"\"\"\n\n def __init__(self):\n self.file_save_name = None\n self.env = None\n self.storage = None\n\n def set_up_full_storage(self, env, path_folder: str, title: str = \"\") -> None:\n r\"\"\"\n Set up the storage to save and update incoming data with passing a reference of the env\n\n file_save_name: will be formatted path_folder\\YYYY-MM-DDTHH-MM-SS__{title}__FULL_DATA_STORAGE.pkl\n\n :param env: The gym environment\n :param path_folder: Path to folder\n :param title: Optional title for addendum\n :return: None\n \"\"\"\n # Reference the gym environment\n self.env = env\n\n # Some variables for saving the file\n utc_str = datetime.datetime.utcnow().strftime('%Y_%m_%dT%H_%M_%S')\n if len(path_folder) > 0:\n os.makedirs(path_folder, exist_ok=True) # Create folder if not exists yet\n self.file_save_name = os.path.join(path_folder, f\"{utc_str}__{title}__FULL_DATA_STORAGE.pkl\")\n\n cum_rewards_arr = ArrayList(env.cum_reward_arr)\n rewards_arr = ArrayList(env.last_reward_arr)\n self.storage = {\n \"title\": title,\n \"cum_rewards\": cum_rewards_arr,\n \"rewards\": rewards_arr,\n \"meta_data_reward\": env.meta_data_reward,\n \"n_cont_rewards\": env.n_cont_rewards,\n \"infos\": []\n }\n\n def update(self) -> None:\n \"\"\"\n should be called in the end of each episode\n\n :return: None\n \"\"\"\n\n self.storage[\"cum_rewards\"].add_row(self.env.cum_reward_arr)\n self.storage[\"rewards\"].add_row(self.env.last_reward_arr)\n self.storage[\"infos\"].append(self.env.info)\n\n def save(self) -> str:\n \"\"\"\n Function to save the pickle file, must be called from the outside, since the gym environment does not know when\n its simulation ends\n\n :return: path to where file is saved\n \"\"\"\n\n self.storage[\"cum_rewards\"] = self.storage[\"cum_rewards\"].get_nparray()\n self.storage[\"rewards\"] = self.storage[\"rewards\"].get_nparray()\n\n with open(self.file_save_name, 'wb') as outp: # Overwrites any existing file.\n pickle.dump(self.storage, outp, pickle.HIGHEST_PROTOCOL)\n\n logger.info(f\"Successfully saved FullDataStorage at {self.file_save_name}\")\n\n return self.file_save_name\n\n def load(self, file_name: str) -> dict:\n \"\"\"\n Function to load an existing full data storage\n\n :param file_name: path to file\n :return: the loaded storage\n \"\"\"\n with open(file_name, 'rb') as inp:\n self.storage = pickle.load(inp)\n return self.storage\n\n def plot_rewards(self):\n \"\"\"\n Individual wrapper for plotting rewards\n :return:\n \"\"\"\n EpisodeVisualization.plot_rewards(cum_rewards=self.storage[\"cum_rewards\"],\n rewards=self.storage[\"rewards\"],\n episode=\"all\",\n title=self.storage[\"title\"],\n x_title=\"episode no.\",\n meta_data_reward=self.storage[\"meta_data_reward\"],\n n_cont_rewards=self.storage[\"n_cont_rewards\"]\n )\n\n\nclass ArrayList:\n \"\"\"\n Custom data type that works as fast as a python list with memory optimization as in numpy\n\n Background: np.append, np.concatenate, np.vstack are very slow, however, it is necessary for the storage classes\n to grow their array size dynamically and represent the data array so far retrieved for the live animation.\n Already with only 100k function calls it takes a minutes for numpy array to concatenate, while appending list\n like or preallocation takes 0.5 seconds here. More on that here:\n https://stackoverflow.com/questions/7133885/fastest-way-to-grow-a-numpy-numeric-array\n https://stackoverflow.com/questions/46102225/which-one-is-faster-np-vstack-np-append-np-concatenate-or-a-manual-function-ma\n\n Arrays are saved based on dimension of first vector in nxc format, where c is the length of the initial vector\n\n :param init_array: any initial array\n \"\"\"\n\n def __init__(self, init_array):\n # Initialize data array\n self.dim_col = init_array.shape\n self.capacity = 100\n self.data = np.zeros((self.capacity, *self.dim_col))\n self.size = 1\n self.data[0, :] = init_array\n\n # Some settings:\n self.array_grow_factor = 4\n\n def __getitem__(self, index):\n return self.data[:self.size][index]\n\n def add_row(self, row: np.ndarray) -> None:\n if self.size == self.capacity:\n self.capacity *= self.array_grow_factor\n newdata = np.zeros((self.capacity, *self.dim_col))\n newdata[:self.size, :] = self.data\n self.data = newdata\n\n self.data[self.size, :] = row\n self.size += 1\n\n def get_nparray(self) -> np.ndarray:\n return self.data[:self.size]\n\n\nclass EpisodeDataStorage:\n r\"\"\"\n Class to save data e.g. vehicle related data during a simulation (e.g. one episode) or env information (e.g.\n reward, observations). Initialize and update after all other initialization and updates\n\n This data is saved in dictionaries, the keys for retrieval are going to be defined here. This class is highly\n individually written to save gym data and use wrapper around other functions.\n\n For the definition of the arrays, please refer to the vehicle documentation.\n\n To add data, if it is an array, use the class ArrayList, which is faster. Make sure to update the setup function,\n update function and the save function accordingly.\n\n .. note::\n\n This structure can also be used to load the data and make it more convenient to retrieve specific data again\n by the property functions. However one must keep in mind: during the simulation process, the data type of the\n arrays in the self.storage dictionary are custom defined ArrayList and do not offer all possibilities like\n the numpy arrays.\n\n Pickle Structure (will be one dict):\n\n .. code-block:: json\n\n {\n \"vehicle\":\n {\n \"object\": \"auvsim.instance (initial one)\",\n \"states\": \"auvsim.state nx12 array\",\n \"states_dot\": \"auvsim._state_dot nx12 array\",\n \"u\": \"auvsim.u nxa array (a number of action)\"\n },\n \"radar\": \"Array with radar end points\",\n \"nu_c\": \"water current\",\n \"shapes\": \"list of shape objects as in shapes.py used here\",\n \"title\": \"title of run\",\n \"episode\": \"episode number\",\n \"step_size\": \"step_size in simulation\",\n \"cum_rewards\": \"cumulative reward array\",\n \"rewards\": \"reward array per step\",\n \"meta_data_reward\": \"List of string for reward description\",\n \"observation\": \"Array with observations as in environment\"\n }\n\n \"\"\"\n\n def __init__(self):\n self.storage = None\n self.vehicle = None\n self.radar = None\n self.file_save_name = None\n self.env = None\n\n def set_up_episode_storage(self, path_folder: str, vehicle: AUVSim, step_size: float,\n nu_c_init: np.ndarray, shapes: List[Shape] = None,\n radar: Radar = None, title: str = \"\", episode: int = -1,\n env=None\n ) -> None:\n r\"\"\"\n Set up the storage to save and update incoming data, including passing a reference to the vehicle and\n environment\n\n file_save_name: will be formatted path_folder\\YYYY-MM-DDTHH-MM-SS__{title}__EPISODE_{episode}_DATA_STORAGE.pkl\n\n\n :param path_folder: Path to folder\n :param vehicle: Vehicle that is simulated\n :param step_size: Stepsize used in this simulation\n :param nu_c_init: water current information in the simulation (body frame) array 6x1\n :param shapes: Shapes for 3d Animation that were used (static)\n :param radar: Radar sensor if used, save endpoints for post visualization\n :param title: Optional title for addendum\n :param episode: Episode number\n :param env: The gym environment\n :return: None\n \"\"\"\n # Some variables for saving the file\n utc_str = datetime.datetime.utcnow().strftime('%Y_%m_%dT%H_%M_%S')\n if len(path_folder) > 0:\n os.makedirs(path_folder, exist_ok=True) # Create folder if not exists yet\n self.file_save_name = os.path.join(path_folder, f\"{utc_str}__{title}__EPISODE_{episode}_DATA_STORAGE.pkl\")\n self.vehicle = vehicle # Vehicle instance (not a copy, automatically a reference which is updated in reference)\n if shapes is None:\n shapes = []\n self.radar = radar # Can still be none!\n # Condition statements for saving data in one line\n end_pos_n = ArrayList(radar.end_pos_n) if radar is not None else None\n # Environment safing related stuff\n self.env = env # This acts as a permanent reference1\n if env is not None:\n cum_rewards_arr = ArrayList(env.cum_reward_arr)\n rewards_arr = ArrayList(env.last_reward_arr)\n meta_data_reward = env.meta_data_reward\n n_cont_rewards = env.n_cont_rewards\n observation = ArrayList(env.observation)\n meta_data_observation = env.meta_data_observation\n else:\n cum_rewards_arr = None\n rewards_arr = None\n meta_data_reward = None\n n_cont_rewards = None\n observation = None\n meta_data_observation = None\n\n self.storage = {\n \"vehicle\": {\n \"object\": vehicle,\n \"states\": ArrayList(self.vehicle.state),\n \"states_dot\": ArrayList(self.vehicle._state_dot),\n \"u\": ArrayList(self.vehicle.u),\n },\n \"radar\": end_pos_n,\n \"nu_c\": ArrayList(nu_c_init),\n \"shapes\": [deepcopy(shape) for shape in shapes],\n \"title\": title,\n \"episode\": episode,\n \"step_size\": step_size,\n \"cum_rewards\": cum_rewards_arr,\n \"rewards\": rewards_arr,\n \"meta_data_reward\": meta_data_reward,\n \"n_cont_rewards\": n_cont_rewards,\n \"observation\": observation,\n \"meta_data_observation\": meta_data_observation,\n }\n\n def update(self, nu_c: np.ndarray) -> None:\n \"\"\"\n should be called in the end of each simulation step\n\n :param nu_c: water current at that time array 6x1\n :param cum_rewards: 1d array with cumulative rewards\n :param rewards: 1d array with rewards\n :return: None\n \"\"\"\n self.storage[\"vehicle\"][\"states\"].add_row(self.vehicle.state)\n self.storage[\"vehicle\"][\"states_dot\"].add_row(self.vehicle._state_dot)\n self.storage[\"vehicle\"][\"u\"].add_row(self.vehicle.u)\n self.storage[\"nu_c\"].add_row(nu_c)\n if self.env is not None:\n self.storage[\"cum_rewards\"].add_row(self.env.cum_reward_arr)\n self.storage[\"rewards\"].add_row(self.env.last_reward_arr)\n self.storage[\"observation\"].add_row(self.env.observation)\n if self.radar is not None:\n self.storage[\"radar\"].add_row(self.radar.end_pos_n)\n\n def save(self) -> str:\n \"\"\"\n Function to save the pickle file\n\n :return: path to where file is saved\n \"\"\"\n # TODO: think about doing this automatically, but I like explicit\n self.storage[\"vehicle\"][\"states\"] = self.storage[\"vehicle\"][\"states\"].get_nparray()\n self.storage[\"vehicle\"][\"states_dot\"] = self.storage[\"vehicle\"][\"states_dot\"].get_nparray()\n self.storage[\"vehicle\"][\"u\"] = self.storage[\"vehicle\"][\"u\"].get_nparray()\n if self.env is not None:\n self.storage[\"cum_rewards\"] = self.storage[\"cum_rewards\"].get_nparray()\n self.storage[\"rewards\"] = self.storage[\"rewards\"].get_nparray()\n self.storage[\"observation\"] = self.storage[\"observation\"].get_nparray()\n if self.radar is not None:\n self.storage[\"radar\"] = self.storage[\"radar\"].get_nparray()\n\n with open(self.file_save_name, 'wb') as outp: # Overwrites any existing file.\n pickle.dump(self.storage, outp, pickle.HIGHEST_PROTOCOL)\n\n logger.info(f\"Successfully saved EpisodeDataStorage at {self.file_save_name}\")\n\n return self.file_save_name\n\n def load(self, file_name: str) -> dict:\n \"\"\"\n Function to load an existing storage\n\n :param file_name: path to file\n :return: the loaded storage\n \"\"\"\n with open(file_name, 'rb') as inp:\n self.storage = pickle.load(inp)\n return self.storage\n\n @property\n def states(self):\n return self.storage[\"vehicle\"][\"states\"][:]\n\n @property\n def positions(self) -> np.ndarray:\n r\"\"\"\n Returns ALL the position of the AUV in NED coordinates x, y, z\n\n :return: nx3 array\n \"\"\"\n return self.storage[\"vehicle\"][\"states\"][:, 0:3]\n\n @property\n def attitudes(self) -> np.ndarray:\n r\"\"\"\n Returns ALL the attitude (euler angles) of the AUV wrt. to NED coordinates roll, pitch, yaw.\n\n :return: nx3 array\n \"\"\"\n return self.storage[\"vehicle\"][\"states\"][:, 3:6]\n\n @property\n def step_size(self) -> float:\n return self.storage[\"step_size\"]\n\n @property\n def u(self) -> np.ndarray:\n return self.storage[\"vehicle\"][\"u\"][:]\n\n @property\n def nu_c(self) -> np.ndarray:\n return self.storage[\"nu_c\"][:]\n\n def plot_episode_animation(self, t_per_step: float = None, title: str = None) -> None:\n \"\"\"\n Individual wrapper for the animation plot function\n \"\"\"\n if title is None:\n title = self.storage[\"title\"]\n EpisodeVisualization.plot_episode_animation(\n states=self.states,\n episode=self.storage[\"episode\"],\n shapes=self.storage[\"shapes\"],\n radar_end_pos=self.storage[\"radar\"],\n t_per_step=t_per_step,\n title=title\n )\n\n def plot_epsiode_states(self):\n \"\"\"\n Individual wrapper for the static post simulation plot function for states\n :return:\n \"\"\"\n EpisodeVisualization.plot_episode_states(states=self.states, nu_c=self.nu_c,\n step_size=self.storage[\"step_size\"],\n episode=self.storage[\"episode\"],\n title=self.storage[\"title\"])\n\n def plot_u(self):\n \"\"\"\n Individual wrapper for the static post simulation plot function for observations\n :return:\n \"\"\"\n EpisodeVisualization.plot_u(u=self.u,\n step_size=self.storage[\"step_size\"],\n episode=self.storage[\"episode\"],\n title=self.storage[\"title\"])\n\n def plot_observation(self):\n \"\"\"\n Individual wrapper for plotting the observations wih metadata in subplots\n :return:\n \"\"\"\n\n EpisodeVisualization.plot_observation(observation=self.storage[\"observation\"],\n step_size=self.storage[\"step_size\"],\n meta_data_obs=self.storage[\"meta_data_observation\"],\n episode=self.storage[\"episode\"],\n title=self.storage[\"title\"])\n\n def plot_rewards(self):\n \"\"\"\n Individual wrapper for plotting rewards\n :return:\n \"\"\"\n EpisodeVisualization.plot_rewards(cum_rewards=self.storage[\"cum_rewards\"],\n rewards=self.storage[\"rewards\"],\n episode=self.storage[\"episode\"],\n title=self.storage[\"title\"],\n meta_data_reward=self.storage[\"meta_data_reward\"],\n n_cont_rewards=self.storage[\"n_cont_rewards\"]\n )\n\n def save_animation_video(self, save_path: str, fps: int) -> None:\n \"\"\"\n Individual wrapper to save video of loaded storage\n :return:\n \"\"\"\n EpisodeVisualization.save_animation_video(save_path=save_path,\n fps=fps,\n states=self.states,\n episode=self.storage[\"episode\"],\n shapes=self.storage[\"shapes\"],\n radar_end_pos=self.storage[\"radar\"],\n title=self.storage[\"title\"])\n","repo_name":"Erikx3/gym_dockauv","sub_path":"gym_dockauv/utils/datastorage.py","file_name":"datastorage.py","file_ext":"py","file_size_in_byte":17890,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"8918651490","text":"import sys, heapq\nfrom collections import deque\n\ninput = sys.stdin.readline\nINF = int(1e9)\ndef dijkstra():\n\n heap = [(0,s)]\n dist[s] = 0\n\n while heap:\n size, cur = heapq.heappop(heap)\n\n # 현재 노드가 이미 처리된 적이 있는 노드라면 무시\n if dist[cur] < size:\n continue\n\n for nex, nex_size in graph[cur]:\n\n # 최단거리 경로 이면 (거의 최단 경로 찾을 때 활용)\n if visited[cur][nex]:\n continue\n\n new_size = size + nex_size\n # 거리가 더 짧은 경우\n if new_size < dist[nex]:\n dist[nex] = new_size\n heapq.heappush(heap, (new_size, nex))\n\ndef bfs():\n deq = deque()\n deq.append(d)\n while deq:\n v = deq.popleft()\n\n # 시작점 도달하면 도착점에서 다시 탐색X\n if v == s:\n # break하면 다른 최단 경로를 확인할 수 없다.\n continue\n\n for u, p in graph_rev[v]:\n # 도착점에서 출발점으로 갈 때\n # 이전 지점(dist[up_node])에서 up_node까지 거리(rev_size)를 더해서\n # 최단경로에 저장되어 있는 값이 나오면 지난 지점 표시\n if dist[u] + p == dist[v] and not visited[u][v]:\n visited[u][v] = 1\n deq.append(u)\n\n\nwhile True:\n\n n, m = map(int,input().split())\n\n if n == 0 and m == 0:\n break\n\n s, d = map(int,input().split())\n\n graph = [[] for _ in range(n)]\n graph_rev = [[] for _ in range(n)]\n\n visited = [[0]*n for _ in range(n)]\n\n for _ in range(m):\n u, v, p = map(int,input().split())\n graph[u].append((v, p))\n graph_rev[v].append((u, p))\n\n # 최단 거리 저장\n dist = [INF] * n\n dijkstra()\n\n # 도착점에서 출발점으로 최단 경로 추적 (visited에 방문 표시)\n bfs()\n\n # 거의 최단 거리 저장\n dist = [INF] * n\n dijkstra()\n\n if dist[d] == INF:\n print(-1)\n else:\n print(dist[d])\n\n","repo_name":"bu119/TIL","sub_path":"Algorithm/BAEKJOON/플래티넘/5719_거의 최단 경로.py","file_name":"5719_거의 최단 경로.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"19657534985","text":"import inspect\nfrom enum import Enum\nfrom abc import ABC, abstractmethod\nfrom database import BaseModel\n\n\nclass StatusCode(Enum):\n OK = 200,\n FAIL = 400\n\n\nclass Builder(ABC):\n @abstractmethod\n def build(self):\n pass\n\n def get_attributes(self, obj):\n result = []\n for attr in inspect.getmembers(obj):\n if not attr[0].startswith('_'):\n if not inspect.ismethod(attr[1]):\n result.append(attr)\n\n return result\n\n\nclass ResponseBuilder(Builder):\n def __init__(self, status=StatusCode.OK):\n self.set_status(status)\n\n def set_status(self, status):\n if isinstance(status, StatusCode):\n if type(status.value) == tuple:\n self.status = status.value[0]\n else:\n self.status = status.value\n else:\n self.status = status\n\n return self\n\n def add_attribute(self, name, value, **kwargs):\n self.__setattr__(name, value)\n for key in kwargs:\n self.__setattr__(key, kwargs.get(key))\n return self\n\n def add_attribute_status(self, name, status: StatusCode):\n status_name = status.name\n self.__setattr__(name, status_name)\n return self\n\n def add_list(self, name, list):\n self.__setattr__(name, list)\n return self\n\n def add_object(self, name, obj):\n self.__setattr__(name, obj)\n return self\n\n def build(self):\n attrs = super(ResponseBuilder, self).get_attributes(self)\n attrs.reverse()\n self.__setattr__(\"result\", \"{\")\n for attr in attrs:\n key = attr[0]\n value = attr[1]\n if type(value) == str:\n self.result += f'\"{key}\": \"{value}\", '\n elif type(value) == int or type(value) == float:\n self.result += f'\"{key}\": {value}, '\n elif type(value) == list:\n list_str = f'\"{key}\": ['\n for el in value:\n if type(el) == tuple and len(el) == 2:\n list_str += f'\"{el[0]}\": \"{el[1]}\", '\n elif type(el) == dict:\n for k in el.keys():\n list_str += f'\"{k}\": \"{el.get(k)}\", '\n elif isinstance(el, BaseModel):\n attrs = super(ResponseBuilder, self).get_attributes(el)\n obj_str = \"{\"\n for at in attrs:\n ke = at[0]\n va = at[1]\n if type(va) == str:\n obj_str += f'\"{ke}\": \"{va}\", '\n elif type(va) == int or type(va) == float:\n obj_str += f'\"{ke}\": {va}, '\n\n obj_str = obj_str.strip(', ')\n obj_str += \"}, \"\n list_str += obj_str\n\n list_str = list_str.strip(', ')\n list_str += '], '\n self.result += list_str\n elif isinstance(value, BaseModel):\n attrs = super(ResponseBuilder, self).get_attributes(value)\n obj_str = f'\"{key}\": ' + \"{\"\n for at in attrs:\n ke = at[0]\n va = at[1]\n if type(va) == str:\n obj_str += f'\"{ke}\": \"{va}\", '\n elif type(va) == int or type(va) == float:\n obj_str += f'\"{ke}\": {va}, '\n\n obj_str = obj_str.strip(', ')\n obj_str += \"}, \"\n self.result += obj_str\n\n self.result = self.result.strip(', ')\n self.result += '}'\n return self.result\n","repo_name":"alisherKAK/KeyForgeServer","sub_path":"builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41953387569","text":"import pygame\n\nSCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 500, 500\nscreenColor = (255, 255, 255)\nrectColor = (0, 0, 0)\nrectSize = rectWidth, rectHeight = 10, 100\nrectPos = rectX, rectY = 5, 200\nrectPos2 = rectX2, rectY2 = 485, 200\nrectSpeed = 2\ngameRect = pygame.Rect(rectX, rectY, rectWidth, rectHeight)\ngameRect2 = pygame.Rect(rectX2, rectY2, rectWidth, rectHeight)\nballColor = (0, 0, 0)\nballSize = ballWidth, ballHeight = 10,10\nballPos = ballX, ballY = 250, 250\nballSpeed = 1\nx_speed = -2\ny_speed = 1\nplayerA_score = 0\nplayerB_score = 0\nkeyPress = False\n#mytuple = playerA_score, playerB_score\nball = pygame.Rect(ballX, ballY, ballWidth, ballHeight)\nclock = pygame.time.Clock()\ntextScore = str(playerA_score) + \" Score \" + str(playerB_score)\n#ballSize =\n#'%d Score %d' %mytuple\npygame.init()\npygame.display.set_caption(\"Pong Game\")\nsurface = pygame.display.set_mode(SCREEN_SIZE)\nfont = pygame.font.Font('freesansbold.ttf', 32)\ntext = font.render(textScore, True, rectColor)\ntext_Rect = text.get_rect()\ntext_Rect.center = (500//2, 50)\n\ndef move_rect(gameRect):\n if keys[pygame.K_UP]:\n gameRect2.move_ip(0, -rectSpeed)\n elif keys[pygame.K_DOWN]:\n gameRect2.move_ip(0, rectSpeed)\n\ndef move_rect2(gameRect2):\n if keys[pygame.K_w]:\n gameRect.move_ip(0, -rectSpeed)\n elif keys[pygame.K_s]:\n gameRect.move_ip(0, rectSpeed)\n\ndef game_reset():\n ball.update(ballX, ballY, ballWidth, ballHeight)\n gameRect.update(rectX, rectY, rectWidth, rectHeight)\n gameRect2.update(rectX2, rectY2, rectWidth, rectHeight)\n keyPress = 0\n # x_speed = 0\n # y_speed = 0\n\n\n#Game Loop\nwhile True:\n for event in pygame.event.get(): #Listening for Events (key press, times, etc)\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n surface.fill(screenColor)\n surface.blit(text, text_Rect)\n keys = pygame.key.get_pressed()\n move_rect(gameRect)\n move_rect2(gameRect2)\n gameRect.clamp_ip(surface.get_rect())\n gameRect2.clamp_ip(surface.get_rect())\n ball.clamp_ip(surface.get_rect())\n pygame.draw.rect(surface, rectColor, gameRect)\n pygame.draw.rect(surface, rectColor, gameRect2)\n pygame.draw.rect(surface, ballColor, ball)\n #flag for keypress\n\n if keyPress == False:\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n ball.move_ip(x_speed, y_speed)\n keyPress = True\n elif event.key == pygame.K_DOWN:\n ball.move_ip(x_speed, y_speed)\n keyPress = True\n elif event.key == pygame.K_w:\n ball.move_ip(x_speed, y_speed)\n keyPress = True\n elif event.key == pygame.K_s:\n ball.move_ip(x_speed, y_speed)\n keyPress = True\n else:\n ball.move_ip(x_speed, y_speed)\n\n\n if ball.right >= SCREEN_WIDTH:\n #y = list(mytuple)\n #y[1] = playerA_score + 1\n #mytuple = tuple(y)\n playerA_score += 1\n textScore = str(playerA_score) + \" Score \" + str(playerB_score)\n game_reset()\n if ball.left <= 0:\n playerB_score += 1\n textScore = str(playerA_score) + \" Score \" + str(playerB_score)\n #y = list(mytuple)\n #y[1] = playerB_score + 1\n #mytuple = tuple(y)\n game_reset()\n if ball.bottom >= SCREEN_HEIGHT or ball.top <= 0:\n y_speed *= -1\n if ball.colliderect(gameRect) or ball.colliderect(gameRect2):\n x_speed *= -1\n #text = font.render('%d Score %d' %mytuple , True, rectColor)\n surface.blit(text, text_Rect)\n text = font.render(textScore, True, rectColor)\n\n pygame.display.update()\n","repo_name":"djhusto/4160Proj1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"74083107798","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tqdm import trange\nimport geopandas\n\ndef hampel_filter_forloop(array, window_size, n_sigmas=3, normalize=False):\n \n n = len(array)\n k = 1.4826 # scale factor for Gaussian distribution\n \n indices = []\n diff = []\n\n if normalize:\n x = np.arange(n)\n a, b = np.polyfit(x, array, 1)\n array = array - (a * x + b)\n \n for i in range(n):\n if i < window_size:\n x0 = np.median(array[0: window_size])\n mad = k * np.median(np.abs(array[0: window_size] - x0))\n elif i > (n - window_size):\n x0 = np.median(array[n - window_size:n])\n mad = k * np.median(np.abs(array[0: window_size] - x0))\n else:\n x0 = np.median(array[(i - window_size):(i + window_size)])\n mad = k * np.median(np.abs(array[(i - window_size):(i + window_size)] - x0))\n if (np.abs(array[i] - x0) > n_sigmas * mad):\n indices.append(i)\n diff.append((array[i] - x0))\n \n return indices, diff\n\nif __name__ == '__main__':\n # hyper parameters\n delta_temperature = 20\n window_length = 11\n delete_max_min = True\n normalize = False\n\n df = pd.read_csv('data.csv')\n\n # calculate the average temperature\n temperature_column = ['col' + str(i) for i in range(1, 32)]\n # Fahrenheit scale to Celsius scale\n df[temperature_column] = (df[temperature_column] - 32) * 5 / 9\n\n # calculate the normal value\n normal_value = -np.ones(len(df))\n normal_value_idx = -np.ones(len(df))\n\n for i in range(len(df)):\n data = df[i:i + 1][temperature_column].to_numpy().squeeze()\n indices, factor = hampel_filter_forloop(data, window_length, normalize=normalize)\n if len(factor) != 0:\n factor = np.array(factor)\n if delete_max_min:\n data_w_o_max_min = data[(data != data.max()) & (data != data.min())]\n std = data_w_o_max_min.std()\n else:\n std = data.std()\n factor = np.abs(factor / std)\n max_factor_idx = np.argmax(factor)\n max_idx = indices[max_factor_idx]\n normal_value[i] = factor[max_factor_idx]\n normal_value_idx[i] = max_idx\n\n success_num = np.zeros(len(df))\n\n with trange(len(df)) as t:\n for i in t:\n for j in range(31):\n data = df[i:i+1][temperature_column].to_numpy().squeeze()\n data[j] += delta_temperature\n indices, factor = hampel_filter_forloop(data, window_length, normalize=normalize)\n if len(factor) != 0:\n factor = np.array(factor)\n\n if delete_max_min:\n data_w_o_max_min = data[(data != data.max()) & (data != data.min())]\n std = data_w_o_max_min.std()\n else:\n std = data.std()\n\n factor = np.abs(factor / std)\n max_factor_idx = np.argmax(factor)\n max_idx = indices[max_factor_idx]\n if (factor[max_factor_idx] > np.max(normal_value)) and (max_idx == j):\n success_num[i] += 1\n\n # merge the success num and df\n df['success_num'] = success_num\n world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))\n \n # split the data into 6 parts\n color_order = ['purple', 'blue', 'green', 'yellow', 'orange', 'red']\n max_val = max(df['success_num'])\n min_val = min(df['success_num'])\n step = (max_val - min_val) / 6\n ax = world[world.name == 'United States of America'].plot(color='white', edgecolor='black')\n for i in range(6):\n sub_df = df[(df['success_num'] >= min_val + step * i) & (df['success_num'] < min_val + step * (i + 1))]\n gdf = geopandas.GeoDataFrame(sub_df, geometry=geopandas.points_from_xy(sub_df.col33, sub_df.col32))\n gdf.plot(ax=ax, color=color_order[i], markersize=1, label=f'{min_val + step * i:.2f} - {min_val + step * (i + 1):.2f}')\n plt.legend()\n plt.title('success_num')\n plt.savefig('success_num.png')\n","repo_name":"Ther-nullptr/DSP-Final-Lab","sub_path":"experiments/03-time-domain-detection-analyse.py","file_name":"03-time-domain-detection-analyse.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"34550268157","text":"import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL\nimport tensorflow as tf\nimport cv2\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nfrom sklearn.model_selection import train_test_split\nimport pathlib\nfrom skimage.io import imread, imshow\nfrom PIL import Image as im\nimport shutil\nfrom sklearn import preprocessing\nle = preprocessing.LabelEncoder()\nimg_width = 128\nimg_height = 128\nbatch_size=32\nimg_channels = 3\nepochs=20\n\n\ndata_dir=os.path.join (r\"C:\\Users\\Nasir\\PycharmProjects\\my\\dataset\")\ndata_dir=pathlib.Path(data_dir)\n\nimglist=os.listdir(data_dir)\nimagelen=len(imglist)\n\noriginal=np.zeros((imagelen, img_height, img_width, img_channels))\nForged=np.zeros((imagelen, img_height, img_width, img_channels))\nMasked=np.zeros((imagelen, img_height, img_width, img_channels))\n\n\n\ni=0\nnum=0\nwhile (num*26<(imagelen)):\n for n in range(25):\n\n img1 = os.path.join(data_dir, imglist[26*num])\n img1 = cv2.imread(img1)\n img1 = img1 / 255.0\n newimage1 = cv2.resize(img1, (img_width, img_height))\n Masked[i+n]=newimage1\n\n img2 = os.path.join(data_dir, imglist[26 * num + (n + 1)])\n img2 = cv2.imread(img2)\n img2 = img2 / 255.0\n newimage2 = cv2.resize(img2, (img_width, img_height))\n Forged[i + n] = newimage2\n\n img3 = os.path.join(data_dir, imglist[26 * num + (n + 27)])\n img3 = cv2.imread(img3)\n img3 = img3 / 255.0\n newimage3 = cv2.resize(img3, (img_width, img_height))\n original[i + n] = newimage3\n num+=2\n i+=25\nMasked=Masked[0:i-25+n+1]\nForged=Forged[0:i-25+n+1]\noriginal=original[0:i-25+n+1]\nprint(\"The size of Masked Images is :\",len(Masked))\nprint(\"The size of Forged Images is :\",len(Forged))\nprint(\"The size of Original Images is :\",len(original))\n\n#window_name = 'image'\n#cv2.imshow(window_name, Masked[25])\n#cv2.waitKey(0)\n\nimages=np.concatenate((original, Forged))\nprint(\"The size of concentated Images is :\",(len(images)))\n\nlabels=np.zeros(len(images))\nlabels[0:int(len(images)/2)-1]=0\nlabels[int(len(images)/2):len(images)-1]=1\nclasses=['Original','Forged']\nclasslength=len(classes)\n#plt.figure(figsize=(10,10))\n#for t in range(25):\n #plt.subplot(5,5,t+1)\n #plt.xticks([])\n #plt.yticks([])\n #plt.grid(False)\n #plt.imshow(images[t+9475])\n\n#plt.show()\n#print(labels[4875])\n\ntrainimg, testimage = train_test_split(images, test_size=0.1, random_state=42)\ntrainlabel, testlabel = train_test_split(labels, test_size=0.1, random_state=42)\n\n\n\n\ninputs = tf.keras.layers.Input((img_height, img_width, img_channels))\n\nc1 = tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_initializer='he_normal', padding='same')(inputs)\nc1 = tf.keras.layers.Dropout(0.1)(c1)\np1 = tf.keras.layers.MaxPooling2D((2, 2))(c1)\n\nc2 = tf.keras.layers.Conv2D(64, 3, activation='relu', kernel_initializer='he_normal', padding='same')(p1)\nc2 = tf.keras.layers.Dropout(0.2)(c2)\np2 = tf.keras.layers.MaxPooling2D((2, 2))(c2)\nc3 = tf.keras.layers.Conv2D(64, 3, activation='relu', kernel_initializer='he_normal', padding='same')(p2)\nc3 = tf.keras.layers.Dropout(0.4)(c3)\np3 = tf.keras.layers.MaxPooling2D((2, 2))(c3)\n\n\np4=tf.keras.layers.Flatten()(p3)\np5=tf.keras.layers.Dense(512, activation='relu')(p4)\ntf.keras.layers.BatchNormalization()\np6 = tf.keras.layers.Dense(512, activation='relu')(p5)\ntf.keras.layers.BatchNormalization()\np7 = tf.keras.layers.Dense(128, activation='relu')(p6)\ntf.keras.layers.BatchNormalization()\n\n\noutputs = tf.keras.layers.Dense(1, activation='sigmoid')(p7)\n\n\nmodel = tf.keras.Model(inputs=[inputs], outputs=[outputs])\n\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()\n\n\n\n\nhistory= model.fit(trainimg, trainlabel, batch_size=batch_size, epochs=epochs,validation_data=(testimage, testlabel))\n\npredictions = model.predict(testimage)\n\n\ntest_img_number = np.random.randint(0, len(testimage))\ntest_loss, test_acc = model.evaluate(testimage, testlabel, verbose=1)\nprint(\"The test accuracy is:\", test_acc)\nscore = tf.nn.softmax(predictions[test_img_number])\nprint('Preictions about Forgery:',classes[np.argmax(score)])\n\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()\n\n","repo_name":"IqbalNasar/Copy-Paste-Forgery-Detection-and-Localization-in-Images-Using-Deep-Learning","sub_path":"Classification.py","file_name":"Classification.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33849493571","text":"import asyncio\nfrom logging import Logger\n\nimport pytest\nimport websockets\nfrom asynctest import CoroutineMock, Mock, MagicMock, patch\nfrom shortid import ShortId\n\nfrom aioidex import IdexDatastream\nfrom aioidex.exceptions import IdexDataStreamError, IdexResponseSidError, IdexHandshakeException\nfrom aioidex.datastream.sub_manager import SubscriptionManager\n\n\n@pytest.fixture()\nasync def ds():\n ds = IdexDatastream()\n yield ds\n\n\n@pytest.mark.asyncio\nasync def test_init():\n api_key = 'testkey'\n version = '0.0.1'\n ws_endpoint = 'wss://end.point'\n handshake_timeout = 3.21\n return_sub_responses = True\n loop = asyncio.get_event_loop()\n\n ds = IdexDatastream(\n api_key,\n version,\n ws_endpoint,\n handshake_timeout,\n return_sub_responses,\n loop,\n )\n\n assert ds._API_KEY == api_key\n assert ds._WS_ENDPOINT == ws_endpoint\n assert ds._WS_VERSION == version\n assert ds._HANDSHAKE_TIMEOUT == handshake_timeout\n assert ds._loop is loop\n assert isinstance(ds._logger, Logger)\n assert isinstance(ds._rid, ShortId)\n assert isinstance(ds.sub_manager, SubscriptionManager)\n\n\n@pytest.mark.asyncio\nasync def test_check_connection(ds: IdexDatastream):\n ds.init = CoroutineMock()\n\n ds._ws = object\n await ds._check_connection()\n ds.init.assert_not_awaited()\n\n ds._ws = None\n await ds._check_connection()\n ds.init.assert_awaited_once()\n\n\n@pytest.mark.asyncio\nasync def test_init_ds(ds: IdexDatastream):\n ds._init_connection = CoroutineMock()\n ds._shake_hand = CoroutineMock()\n\n await ds.init()\n\n ds._init_connection.assert_awaited_once()\n ds._shake_hand.assert_awaited_once()\n\n\n@pytest.mark.asyncio\nasync def test_init_connection(ds: IdexDatastream):\n ws_mock = Mock()\n create_conn_mock = CoroutineMock(return_value=ws_mock)\n ds.create_connection = create_conn_mock\n\n await ds._init_connection()\n\n create_conn_mock.assert_awaited_once()\n assert ds._ws is ws_mock\n\n another_mock_ws = Mock()\n\n await ds._init_connection(another_mock_ws)\n\n assert ds._ws is another_mock_ws\n\n\n@pytest.mark.asyncio\nasync def test_create_connection(ds: IdexDatastream):\n ds._check_connection = CoroutineMock()\n ds._get_rid = Mock(return_value='rid:smth')\n ds._compose_message = Mock(return_value={'some': 'data'})\n ds._ws = Mock()\n ds._ws.send = CoroutineMock()\n ds._encode = Mock()\n\n result = await ds.send_message('some_request', {'some': 'payload'})\n\n ds._check_connection.assert_awaited_once()\n ds._get_rid.assert_called_once()\n ds._compose_message.assert_called_once_with('rid:smth', 'some_request', {'some': 'payload'})\n ds._encode.assert_called_once_with({'some': 'data'})\n ds._ws.send.assert_awaited_once()\n assert result == 'rid:smth'\n\n\n@pytest.mark.asyncio\nasync def test_create_connection_rid(ds: IdexDatastream):\n ds._check_connection = CoroutineMock()\n ds._get_rid = Mock(return_value='rid:smth')\n ds._compose_message = Mock(return_value={'some': 'data'})\n ds._ws = Mock()\n ds._ws.send = CoroutineMock()\n ds._encode = Mock()\n\n result = await ds.send_message('some_request', {'some': 'payload'}, 'somerid')\n\n ds._check_connection.assert_awaited_once()\n ds._get_rid.assert_not_called()\n ds._compose_message.assert_called_once_with('somerid', 'some_request', {'some': 'payload'})\n ds._encode.assert_called_once_with({'some': 'data'})\n ds._ws.send.assert_awaited_once()\n assert result == 'somerid'\n\n\ndef test_compose_message(ds: IdexDatastream):\n ds._set_sid('somesid')\n assert ds._compose_message('somerid', 'somerequest', {'some': 'payload'}) == dict(\n rid='somerid',\n sid='somesid',\n request='somerequest',\n payload={'some': 'payload'}\n )\n\n\n@pytest.mark.asyncio\nasync def test_listen(ds: IdexDatastream):\n msg_data = '{\"payload\":\"{\"some\": \"data\"}\"}'\n\n ds._check_connection = CoroutineMock()\n ds._ws = MagicMock()\n ds._ws.closed = False\n ds._ws.__aiter__.return_value = (msg_data,)\n\n processed_message = {'a': 'b'}\n ds._process_message: Mock = Mock()\n ds._process_message.return_value = processed_message\n\n msg = None\n async for m in ds.listen():\n msg = m\n break\n\n ds._process_message.assert_called_once_with(msg_data)\n assert msg == processed_message\n\n\n@pytest.mark.asyncio\nasync def test_listen_reconnect(ds: IdexDatastream):\n class BreakExc(Exception):\n pass\n\n exc = websockets.ConnectionClosed(code=999, reason='some reason')\n exit_exc = BreakExc('to break the infinite loop')\n\n ds._check_connection = CoroutineMock()\n ds._ws = MagicMock()\n ds._ws.closed = False\n ds._ws.__aiter__.side_effect = exc\n\n ds.init = CoroutineMock()\n\n ds.sub_manager.resubscribe = CoroutineMock()\n ds.sub_manager.resubscribe.side_effect = exit_exc\n\n ds._logger.error = Mock()\n\n with pytest.raises(BreakExc):\n async for m in ds.listen():\n break\n\n ds._check_connection.assert_awaited_once()\n ds._logger.error.assert_called_once_with(exc)\n ds.init.assert_awaited_once()\n ds.sub_manager.resubscribe.assert_awaited_once()\n\n\n@pytest.mark.asyncio\nasync def test_listen_raise(ds: IdexDatastream):\n class UnhandledExc(Exception):\n pass\n\n exc = UnhandledExc('some unknown exception')\n\n ds._check_connection = CoroutineMock()\n ds._ws = MagicMock()\n ds._ws.closed = False\n ds._ws.__aiter__.side_effect = exc\n\n with pytest.raises(UnhandledExc):\n async for m in ds.listen():\n break\n\n ds._check_connection.assert_awaited_once()\n\n\ndef test_process_message(ds: IdexDatastream):\n msg = '{\"payload\":\"{\"some\": \"data\"}\"}'\n decoded_msg = {1: 2}\n\n ds._decode = Mock()\n ds._decode.return_value = decoded_msg\n\n ds._check_warnings = Mock()\n ds._check_errors = Mock()\n ds._check_sid = Mock()\n\n ds.sub_manager.is_sub_response = Mock()\n ds.sub_manager.is_sub_response.return_value = False\n\n result = ds._process_message(msg)\n\n ds._decode.assert_called_once_with(msg)\n ds.sub_manager.is_sub_response.assert_called_once_with(decoded_msg)\n ds._check_warnings.assert_called_once_with(decoded_msg)\n ds._check_errors.assert_called_once_with(decoded_msg)\n ds._check_sid.assert_called_once_with(decoded_msg)\n\n assert result == decoded_msg\n\n\ndef test_process_message_sub_response(ds: IdexDatastream):\n msg = '{\"payload\":\"{\"some\": \"data\"}\"}'\n decoded_msg = {1: 2}\n sub_response = {3: 4}\n\n ds._decode = Mock()\n ds._decode.return_value = decoded_msg\n\n ds._check_warnings = Mock()\n ds._check_errors = Mock()\n ds._check_sid = Mock()\n\n ds.sub_manager.is_sub_response = Mock()\n ds.sub_manager.is_sub_response.return_value = True\n\n ds.sub_manager.process_sub_response = Mock()\n ds.sub_manager.process_sub_response.return_value = sub_response\n\n result = ds._process_message(msg)\n\n ds._decode.assert_called_with(msg)\n ds.sub_manager.is_sub_response.assert_called_once_with(decoded_msg)\n ds.sub_manager.process_sub_response.assert_called_once_with(decoded_msg)\n ds._check_warnings.assert_called_once_with(decoded_msg)\n ds._check_errors.assert_called_once_with(decoded_msg)\n ds._check_sid.assert_called_once_with(decoded_msg)\n\n assert result == sub_response\n\n\ndef test_check_warnings_exists(ds: IdexDatastream):\n msg = {'warnings': ['warning1', 'warning2']}\n\n ds._logger.warning = Mock()\n\n ds._check_warnings(msg)\n\n assert ds._logger.warning.call_count == 2\n\n\ndef test_check_warnings_not_exists(ds: IdexDatastream):\n msg = {}\n\n ds._logger.warning = Mock()\n\n ds._check_warnings(msg)\n\n ds._logger.warning.assert_not_called()\n\n\ndef test_check_error_exists(ds: IdexDatastream):\n msg = {'result': 'error', 'payload': {'message': 'error message'}}\n\n with pytest.raises(IdexDataStreamError):\n ds._check_errors(msg)\n\n\ndef test_check_error_not_exists(ds: IdexDatastream):\n msg = {'result': 'success'}\n\n ds._check_errors(msg)\n\n\ndef test_check_sid_raise(ds: IdexDatastream):\n ds._sid = 'sid:one'\n\n msg = {'sid': 'sid:another'}\n\n with pytest.raises(IdexResponseSidError):\n ds._check_sid(msg)\n\n\ndef test_check_sid_not_raise(ds: IdexDatastream):\n ds._sid = 'sid:one'\n\n msg = {'sid': ds._sid}\n\n ds._check_sid(msg)\n\n\n@pytest.mark.asyncio\nasync def test_shake_hand(ds: IdexDatastream):\n ds._WS_VERSION = 'v1'\n ds._API_KEY = 'key'\n\n handshake_result = 'some result'\n\n ds._set_sid = Mock()\n ds.send_message = CoroutineMock()\n ds._wait_for_handshake_response = CoroutineMock()\n ds._wait_for_handshake_response.return_value = handshake_result\n ds._process_handshake_response = Mock()\n\n await ds._shake_hand()\n\n ds._set_sid.assert_called_with(None)\n ds.send_message.assert_awaited_once_with('handshake', dict(version='v1', key='key'))\n ds._wait_for_handshake_response.assert_awaited_once()\n ds._process_handshake_response.assert_called_once_with(handshake_result)\n\n\n@pytest.mark.asyncio\nasync def test_wait_for_handshake_response(ds: IdexDatastream):\n ds._ws = CoroutineMock()\n\n loop_mock = CoroutineMock()\n ds._loop = loop_mock\n\n recv_mock = Mock()\n recv_mock.return_value = None\n ds._ws.recv = recv_mock\n\n with patch('asyncio.wait_for', new=CoroutineMock()) as mock:\n mock.return_value = '{\"some\":\"data\"}'\n await ds._wait_for_handshake_response()\n\n mock.assert_awaited_once_with(None, ds._HANDSHAKE_TIMEOUT, loop=loop_mock)\n\n\ndef test_process_handshake_response(ds: IdexDatastream):\n ds._set_sid = Mock()\n\n with pytest.raises(IdexHandshakeException):\n ds._process_handshake_response({'result': 'not_success'})\n\n with pytest.raises(IdexHandshakeException):\n ds._process_handshake_response({'result': 'success', 'request': 'not_handshake'})\n\n ds._process_handshake_response({'result': 'success', 'request': 'handshake', 'sid': 'some_sid'})\n ds._set_sid.assert_called_once_with('some_sid')\n\n\ndef test_get_rid(ds: IdexDatastream):\n rid = ds._get_rid()\n\n assert isinstance(rid, str)\n assert rid.startswith('rid:')\n # Max accepted length is 50 characters. Your rid will be truncated if any longer than this.\n # Clients sending rid's which are longer than 50 characters risk eventual disconnects, blacklisting, or bans.\n assert len(rid) <= 50\n\n rid2 = ds._get_rid()\n assert rid != rid2\n\n\ndef test_sid(ds: IdexDatastream):\n ds._logger.info = Mock()\n\n ds._set_sid('some_sid')\n\n ds._logger.info.assert_called_once()\n assert ds._sid == 'some_sid'\n\n\ndef test_sid_equal(ds: IdexDatastream):\n ds._logger.info = Mock()\n\n ds._sid = 'some_sid'\n ds._set_sid('some_sid')\n\n ds._logger.info.assert_not_called()\n assert ds._sid == 'some_sid'\n\n\ndef test_encode(ds: IdexDatastream):\n data = {'some': 'data', 'arr': [{'k1': 'v1'}, {'k2': 'v2'}]}\n expected = '{\"some\":\"data\",\"arr\":[{\"k1\":\"v1\"},{\"k2\":\"v2\"}]}'\n\n assert ds._encode(data) == expected\n\n\ndef test_decode(ds: IdexDatastream):\n assert ds._decode('{\"some\":\"data\"}') == {'some': 'data'}\n assert ds._decode('{\"payload\": \"{\\\\\"some\\\\\": \\\\\"data\\\\\"}\"}') == {'payload': {'some': 'data'}}\n assert ds._decode('{\"warnings\": \"[\\\\\"warn1\\\\\", \\\\\"warn2\\\\\"]\"}') == {'warnings': ['warn1', 'warn2']}\n","repo_name":"ape364/aioidex","sub_path":"aioidex/tests/test_datastream.py","file_name":"test_datastream.py","file_ext":"py","file_size_in_byte":11294,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"85"} +{"seq_id":"12403325902","text":"# SAFE TEAM\n#\n#\n# distributed under license: CC BY-NC-SA 4.0 (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.txt) #\n#\nimport json\nimport r2pipe\nimport capstone\nimport binascii\nimport traceback\n\nclass RadareFunctionAnalyzer:\n\n def __init__(self, filename, use_symbol, depth):\n self.r2 = r2pipe.open(filename, flags=['-2'])\n self.filename = filename\n self.arch, self.bits, self.base = self.get_arch()\n self.top_depth = 0\n self.use_symbol = use_symbol\n\n def __enter__(self):\n return self\n\n @staticmethod\n def filter_reg(op):\n return op[\"value\"]\n\n\n def execute_r2_cmd(self, cmd):\n a = self.r2.cmd(cmd)\n if type(a) != str:\n a = a.decode('utf-8')\n return a\n\n @staticmethod\n def filter_imm(op):\n imm = int(op[\"value\"])\n if -int(5000) <= imm <= int(5000):\n ret = str(hex(op[\"value\"]))\n else:\n ret = str('HIMM')\n return ret\n\n @staticmethod\n def filter_mem(op):\n if \"base\" not in op:\n op[\"base\"] = 0\n\n if op[\"base\"] == 0:\n r = \"[\" + \"MEM\" + \"]\"\n else:\n reg_base = str(op[\"base\"])\n disp = str(op[\"disp\"])\n scale = str(op[\"scale\"])\n r = '[' + reg_base + \"*\" + scale + \"+\" + disp + ']'\n return r\n\n @staticmethod\n def filter_memory_references_r(i):\n inst = \"\" + i[\"mnemonic\"]\n\n for op in i[\"operands\"]:\n if op[\"type\"] == 'reg':\n inst += \" \" + RadareFunctionAnalyzer.filter_reg(op)\n elif op[\"type\"] == 'imm':\n inst += \" \" + RadareFunctionAnalyzer.filter_imm(op)\n elif op[\"type\"] == 'mem':\n inst += \" \" + RadareFunctionAnalyzer.filter_mem(op)\n if len(i[\"operands\"]) > 1:\n inst = inst + \",\"\n\n if \",\" in inst:\n inst = inst[:-1]\n inst = inst.replace(\" \", \"_\")\n\n return str(inst)\n \n @staticmethod\n def filter_memory_references(i):\n inst = \"\" + i.mnemonic\n for op in i.operands:\n if (op.type == 1):\n inst = inst + \" \" + i.reg_name(op.reg)\n elif (op.type == 2):\n imm = int(op.imm)\n if (-int(5000) <= imm <= int(5000)):\n inst = inst + \" \" + str(hex(op.imm))\n else:\n inst = inst + \" \" + str('HIMM')\n elif (op.type == 3):\n mem = op.mem\n if (mem.base == 0):\n r = \"[\" + \"MEM\" + \"]\"\n else:\n r = '[' + str(i.reg_name(mem.base)) + \"*\" + str(mem.scale) + \"+\" + str(mem.disp) + ']'\n inst = inst + \" \" + r\n if (len(i.operands) > 1):\n inst = inst + \",\"\n if \",\" in inst:\n inst = inst[:-1]\n inst = inst.replace(\" \", \"_\")\n return str(inst)\n\n @staticmethod\n def get_callref(my_function, depth):\n calls = {}\n if 'callrefs' in my_function and depth > 0:\n for cc in my_function['callrefs']:\n if cc[\"type\"] == \"C\":\n calls[cc['at']] = cc['addr']\n return calls\n\n def get_instruction(self):\n instruction = json.loads(self.execute_r2_cmd(\"aoj 1\"))\n if len(instruction) > 0:\n instruction = instruction[0]\n else:\n return None\n\n operands = []\n if 'opex' not in instruction:\n return None\n\n for op in instruction['opex']['operands']:\n operands.append(op)\n instruction['operands'] = operands\n return instruction\n \n def get_instructions_capstone(self, asm):\n print(\"hello\")\n \n\n def function_to_inst(self, my_function, depth):\n # print(\"INSR\")\n asm = \"\"\n address = 0\n\n if self.use_symbol:\n s = my_function['vaddr']\n else:\n s = my_function['offset']\n self.r2.cmd('s ' + str(s))\n\n if self.use_symbol:\n end_address = s + my_function[\"size\"]\n asm = self.r2.cmd(\"p8 {}\".format(my_function[\"size\"]))\n else:\n end_address = s + my_function[\"realsz\"]\n asm = self.r2.cmd(\"p8 {}\".format(my_function[\"realsz\"]))\n \n asm = asm.strip()\n # print(\"ADDR:\" + str(my_function['offset']))\n binary = binascii.unhexlify(asm)\n\n #if self.arch == 'x86':\n # cs_arch = capstone.CS_ARCH_X86\n cs_arch = capstone.CS_ARCH_X86\n\n if self.bits == 32:\n cs_bits = capstone.CS_MODE_32\n elif self.bits == 64:\n cs_bits = capstone.CS_MODE_64\n else:\n cs_bits = capstone.CS_MODE_64\n\n\n md = capstone.Cs(cs_arch, cs_bits)\n md.detail = True\n instructions = []\n cap_insns = []\n\n for i in md.disasm(binary, s - self.base):\n # print(\"i: \" + str(i))\n instructions.append(self.filter_memory_references(i))\n\n return instructions, asm\n\n def get_arch(self):\n try:\n info = json.loads(self.execute_r2_cmd('ij'))\n if 'bin' in info:\n arch = info['bin']['arch']\n bits = info['bin']['bits']\n base = info['bin']['baddr'] + info['bin']['bits']\n else:\n arch = None\n bits = None\n except:\n traceback.print_exc()\n print(\"Error loading file\")\n arch = None\n bits = None\n return arch, bits, base\n\n def find_functions(self):\n self.r2.cmd('aa')\n self.r2.cmd('aac')\n self.r2.cmd('aar')\n self.r2.cmd('aae')\n self.r2.cmd('aat')\n self.r2.cmd('aap')\n try:\n function_list = json.loads(self.execute_r2_cmd('aflj'))\n except:\n function_list = []\n return function_list\n\n def find_functions_by_symbols(self):\n self.r2.cmd('aa')\n try:\n symbols = json.loads(self.execute_r2_cmd('isj'))\n fcn_symb = [s for s in symbols if s['type'] == 'FUNC']\n except:\n fcn_symb = []\n return fcn_symb\n\n def analyze(self):\n result = {}\n if self.arch == None:\n return result\n if self.use_symbol:\n function_list = self.find_functions_by_symbols()\n function_list = [f for f in function_list if f['size'] > 50]\n else:\n function_list = self.find_functions()\n function_list = [f for f in function_list if f['realsz'] > 50]\n\n for my_function in function_list:\n if self.use_symbol:\n address = my_function['vaddr']\n else:\n address = my_function['offset']\n\n try:\n instructions, asm = self.function_to_inst(my_function, self.top_depth)\n prepappend = 'X_'\n instructions = [prepappend + x for x in instructions]\n result[my_function['name']] = {'filtered_instructions': instructions, \"asm\": asm, \"address\": address}\n except:\n #print(\"Error in functions: {} from {}\".format(my_function['name'], self.filename))\n pass\n return result\n\n def close(self):\n self.r2.quit()\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.r2.quit()\n\n\n\n","repo_name":"lucamassarelli/yarasafe","sub_path":"python_script/FunctionAnalyzerRadare.py","file_name":"FunctionAnalyzerRadare.py","file_ext":"py","file_size_in_byte":7405,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"85"} +{"seq_id":"72124989077","text":"from pandas import read_csv, DataFrame\n\ndef getModel():\n\n\t\n\tmodelFilename = \"./MexicoCases2015-2018.csv\"\n\tmodel = read_csv(modelFilename, index_col=\"CITY\", header=0)\n\n\toutput = DataFrame(index=model.index)\n\n\tfor i in range(2015, 2019):\n\t\tcol = str(i)\n\t\ttemp = model[model.columns[model.columns.str.contains(col)]]\n\t\toutput[col] = temp.sum(axis=1)\n\n\toutput.to_csv(\"yearlyMexico2015-2018.csv\")\n\t\n\n\nif __name__ == '__main__':\n\tdataset = getModel()","repo_name":"kevinislas2/ziknet-trends","sub_path":"data/DatasetToYearly.py","file_name":"DatasetToYearly.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"2800459091","text":"def ttt():\r\n states={}\r\n state=[[0,0,0],[0,0,0],[0,0,0]]\r\n stat=[]\r\n def repopulate():\r\n states[bytes(state)]+=[1,2,3,4,5,6,7,8,9]*3\r\n def open_box():\r\n if not states[bytes(state)]:\r\n repopulate()\r\n go=random.choice(states[bytes(state)])\r\n while not islegal(go):\r\n go=random.choise(states[bytes(state)])\r\n stat.append([state,go])\r\n return go\r\n def update():\r\n for i in stat:\r\n states[bytes(i[0])].remove(i[1])\r\n while not win(state):\r\n inp=yield\r\n if inp ==0:\r\n inp=yield open_box()\r\n","repo_name":"MaxHearnden/tic-tac-toe-ai","sub_path":"tttai.py","file_name":"tttai.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32845251836","text":"class Generator:\n def __init__(self, name, fields):\n self.name = name\n self.fields = fields\n\n def __create_fields(self):\n string = \"\"\n for key, value in self.fields.items():\n if type(value) == str:\n string += \" String \" + key + \";\\n\"\n elif type(value) == int:\n string += \" int \" + key + \";\\n\"\n elif type(value) == float:\n string += \" double \" + key + \";\\n\"\n elif type(value) == list:\n datatype = type(value[0])\n if datatype == str:\n string += \" List \" + key + \";\\n\"\n elif datatype == int:\n string += \" List \" + key + \";\\n\"\n elif datatype == dict:\n string += \" List<\" + key.capitalize() + \"> \" + key + \";\\n\"\n elif type(value) == dict:\n string += \" \" + key.capitalize() + \" \" + key + \";\\n\"\n return string\n\n def __create_constructor(self):\n string = \"%s({\" % self.name\n for key in self.fields.keys():\n string += \"this.\" + key + \",\"\n string = string[:-1] + \"});\\n\"\n return string\n\n def __create_from_json(self):\n string = self.name + \".fromJson(Map json) {\\n\"\n for key, value in self.fields.items():\n if type(value) == list:\n datatype = type(value[0])\n if datatype == str:\n string += \" \" + key + \" = json['\" + key + \"'].cast();\\n\"\n elif datatype == int:\n string += \" \" + key + \" = json['\" + key + \"'].cast();\\n\"\n elif datatype == dict:\n string += \" if(json['\" + key + \"'] != null){\\n \" + key + \" = new List<\" + key.capitalize() + \">();\\n json['\" + key + \"'].forEach((v) {\\n \" + key + \".add(new \" + key.capitalize() + \".fromJson(v));\\n });\\n }\\n \"\n elif type(value) == dict:\n string += \" \" + key + \" = json['\" + key + \"'] != null ? new \" + key.capitalize() + \".fromJson(json['\" + key + \"']) : null;\\n\"\n else:\n string += \" \" + key + \" = json['\" + key + \"'];\\n\"\n string += \" }\\n\"\n return string\n\n def __create_to_json(self):\n string = \"Map toJson() {\\n final Map data = new Map();\\n\"\n for key, value in self.fields.items():\n if type(value) == dict:\n string += \" if (this.\" + key + \" != null){\\n data['\" + key + \"'] = this.\" + key + \".toJson();\\n }\\n\"\n elif type(value) == list:\n dtype = type(value[0])\n if dtype == dict:\n string += \" if (this.\" + key + \" != null) {\\n data['\" + key + \"'] = this.\" + key + \".map((v) => v.toJson()).toList();\\n }\\n\"\n else:\n string += \" data['\" + key + \"'] = this.\" + key + \";\\n\"\n else:\n string += \" data['\" + key + \"'] = this.\" + key + \";\\n\"\n\n string += \" return data;\\n }\"\n return string\n\n def create_class(self):\n fields_initial = self.__create_fields()\n constructor = self.__create_constructor()\n from_json = self.__create_from_json()\n to_json = self.__create_to_json()\n string = \"class %s {\\n%s\\n %s\\n %s\\n %s\\n}\" % (self.name, fields_initial, constructor, from_json, to_json)\n return string\n","repo_name":"parth-p-7span/json2dart-discord-bot","sub_path":"class_generator.py","file_name":"class_generator.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"11830745884","text":"import sys\ninput = sys.stdin.readline\n\nfor _ in range(int(input())):\n clothes_num = int(input())\n clothes = {}\n \n for _ in range(clothes_num):\n clothes_name, clothes_type = input().split()\n \n if clothes_type not in clothes.keys():\n clothes[clothes_type] = 1\n else:\n clothes[clothes_type] += 1\n \n res = 1\n for i in clothes:\n res *= (clothes[i] + 1)\n \n print(res - 1) # 알몸인 경우 제외","repo_name":"pokavv/backjoon","sub_path":"9375_230203.py","file_name":"9375_230203.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1935185525","text":"import numpy as np\nimport random\nfrom collections import defaultdict\n\nclass Agent:\n\n def __init__(self, nA=6):\n \"\"\" Initialize agent.\n\n Params\n ======\n - nA: number of actions available to the agent\n \"\"\"\n self.nA = nA\n self.Q = defaultdict(lambda: np.zeros(self.nA))\n self.epsilon = 0.005\n self.gamma = 0.8 # 1.0\n self.alpha = 0.07 # 0.01\n\n def get_probs(self,Q_s):\n \"\"\" obtains the action probabilities corresponding to epsilon-greedy policy \"\"\"\n policy_s = np.ones(self.nA) * self.epsilon / self.nA\n best_a = np.argmax(Q_s)\n policy_s[best_a] = 1 - self.epsilon + (self.epsilon / self.nA)\n return policy_s\n\n def select_action(self, state):\n \"\"\" Given the state, select an action.\n\n Params\n ======\n - state: the current state of the environment\n\n Returns\n =======\n - action: an integer, compatible with the task's action space\n \"\"\"\n act_space = [i for i in range(0, self.nA)]\n action = np.random.choice(np.arange(self.nA),\n p = self.get_probs(self.Q[state])) if state in self.Q else random.choice(act_space)\n # return np.random.choice(self.nA)\n return action\n\n def step(self, state, action, reward, next_state, done):\n \"\"\" Update the agent's knowledge, using the most recently sampled tuple.\n\n Params\n ======\n - state: the previous state of the environment\n - action: the agent's previous choice of action\n - reward: last reward received\n - next_state: the current state of the environment\n - done: whether the episode is complete (True or False)\n \"\"\"\n # self.Q[state][action] += 1\n # next_state, reward, done, _ = env.step(a_t)\n # print(state,reward,done, prob)\n # 36 -1 False {'prob': 1.0}\n a_t_1 = self.select_action(next_state)\n self.Q[state][action] = self.Q[state][action] + self.alpha * (reward + self.gamma * (self.Q[next_state][a_t_1]) - self.Q[state][action])\n","repo_name":"xsankar/OpenAI-Taxi-V2","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"85"} +{"seq_id":"39368964523","text":"import requests\nfrom bs4 import BeautifulSoup\n\nimport re\nimport datetime\nfrom tqdm import tqdm\nfrom datetime import datetime\n\nimport json\nimport csv\n\nimport multiprocessing\nimport time\n\n\n# 변수 세팅\ncorp_file = './dart_corpCodes.csv' # 기업 리스트 파일\noutput_path = './output/' # output 파일 경로\n\nmax_page = 100 # 네이버 뉴스 몇 페이지를 가져올 건지\nyears = 3 # 몇 년치 뉴스를 가져올 건지\nlisted = True # 상장기업 or 비상장기업\n\n\n\n#회사 목록 리스트에서 상장사, 비상장사 구분하여 가져옴\ndef get_company_list(file_path, listed):\n\n with open(file_path,'r', encoding='utf-8') as f:\n mycsv=csv.reader(f)\n companies=[]\n for row in mycsv:\n company={}\n company['corp_code']=row[0]\n company['corp_name']=row[1]\n company['stock_code']=row[2]\n company['modify_date']=row[3]\n companies.append(company)\n \n cor_listed=[]\n cor_not_listed=[]\n for company in companies:\n if company['stock_code'] == ' ':\n cor_not_listed.append(company)\n else:\n cor_listed.append(company)\n \n if listed:\n return cor_listed\n else:\n return cor_not_listed \n \n\n# 각 기업에 대해서 크롤링 할 최대 페이지 및 기간에 해당하는 뉴스 링크를 가져옴\ndef news_crawler(query, max_page):\n \n start_pg = 1\n end_pg = (int(max_page)-1)*10+1 \n\n naver_urls = [] \n \n while start_pg < end_pg:\n \n url = \"https://search.naver.com/search.naver?where=news&sm=tab_pge&query=\" + query + \"&start=\" + str(start_pg)\n headers = { \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36\" }\n \n raw = requests.get(url, headers=headers)\n cont = raw.content\n html = BeautifulSoup(cont, 'html.parser')\n \n for urls in html.select(\"a.info\"):\n try:\n if \"news.naver.com\" in urls['href']:\n naver_urls.append(urls['href']) \n except Exception as e:\n continue\n \n start_pg += 10\n \n return naver_urls \n\n\n# 각 기업에 대해 뉴스 data 생성\ndef newsdataset(query):\n \n total_news = []\n\n total_urls = news_crawler(query, max_page)\n total_urls = list(set(total_urls)) \n\n headers = { \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36\" }\n\n for url in (total_urls):\n try:\n raw = requests.get(url,headers=headers)\n html = BeautifulSoup(raw.text, \"html.parser\")\n except requests.exceptions.RequestException:\n continue\n \n news={}\n pattern1 = '<[^>]*>'\n\n ## 날짜\n try:\n html_date = html.select_one(\"div#ct> div.media_end_head.go_trans > div.media_end_head_info.nv_notrans > div.media_end_head_info_datestamp > div > span\")\n news_date = html_date.attrs['data-date-time']\n except AttributeError:\n news_date = html.select_one(\"#content > div.end_ct > div > div.article_info > span > em\")\n news_date = re.sub(pattern=pattern1,repl='',string=str(news_date))\n \n start_year = datetime.now().year - years\n try:\n news_year = int(news_date[:4])\n if news_year < start_year:\n continue\n else:\n news['dates']=news_date\n except ValueError:\n continue\n\n # url\n news['url']=url\n\n # 뉴스 제목\n title = html.select(\"div#ct > div.media_end_head.go_trans > div.media_end_head_title > h2\")\n title = ''.join(str(title))\n title = re.sub(pattern=pattern1,repl='',string=title)\n news['titles']=title\n\n #뉴스 본문\n content = html.select(\"div#dic_area\")\n content = ''.join(str(content))\n content = re.sub(pattern=pattern1,repl='',string=content)\n pattern2 = '\\n'\n content = re.sub(pattern=pattern2,repl='',string=content)\n pattern3 = \"\"\"[\\n\\n\\n\\n\\n// flash 오류를 우회하기 위한 함수 추가\\nfunction _flash_removeCallback() {}\"\"\"\n content = content.replace(pattern3,'')\n news['content']=content\n\n total_news.append(news)\n \n # return total_news\n path = output_path + query + '.json' \n with open(path, 'w', encoding='utf-8') as f:\n json.dump(total_news, f, ensure_ascii=False, indent='\\t')\n\n\ndef main():\n\n start_time = time.time()\n\n companies = get_company_list(corp_file, listed)\n queries=[companies[i]['corp_name'] for i in range(1,len(companies))]\n\n with multiprocessing.Pool(4) as pool:\n list(tqdm(pool.imap(newsdataset, queries), total=len(queries)))\n pool.close()\n pool.join()\n\n print(\"---%s seconds ---\" % (time.time() - start_time))\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"KPMG-IDEATHON-NARVIS/NARVIS","sub_path":"Data/news/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"39097718370","text":"import pyautogui\r\nimport matplotlib.pyplot as plt\r\nfrom time import sleep\r\ntemp_x=[]\r\ntemp_y=[]\r\npyautogui.moveTo(1366/2,768/4,0.05)\r\nfor i in range(90):\r\n x = pyautogui.position()\r\n sleep(0.025)\r\n y=(a,b)=pyautogui.position()\r\n if x!=y:\r\n temp_x.append(a)\r\n temp_y.append(b)\r\n print(a,b)\r\nplt.plot(temp_x,temp_y,'ro')\r\nplt.axis([0,1366,768,0])\r\nplt.show()\r\n \r\n \r\n \r\n","repo_name":"Abhinay1997/my_python_scripts","sub_path":"risk.py","file_name":"risk.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"13546858448","text":"# --------------\n# USER INSTRUCTIONS\n#\n# Write a function called stochastic_value that\n# returns two grids. The first grid, value, should\n# contain the computed value of each cell as shown\n# in the video. The second grid, policy, should\n# contain the optimum policy for each cell.\n#\n# --------------\n# GRADING NOTES\n#\n# We will be calling your stochastic_value function\n# with several different grids and different values\n# of success_prob, collision_cost, and cost_step.\n# In order to be marked correct, your function must\n# RETURN (it does not have to print) two grids,\n# value and policy.\n#\n# When grading your value grid, we will compare the\n# value of each cell with the true value according\n# to this model. If your answer for each cell\n# is sufficiently close to the correct answer\n# (within 0.001), you will be marked as correct.\n\ndelta = [[-1, 0], # go up\n [0, -1], # go left\n [1, 0], # go down\n [0, 1]] # go right\n\ndelta_name = ['^', '<', 'v', '>'] # Use these when creating your policy grid.\n\n# ---------------------------------------------\n# Modify the function stochastic_value below\n# ---------------------------------------------\n\n\ndef isValidCell(grid, x, y):\n if (x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0])):\n return False\n return grid[x][y] == 0\n\n\ndef stochastic_value(grid, goal, cost_step, collision_cost, success_prob):\n # Probability(stepping left) = prob(stepping right) = failure_prob\n failure_prob = (1.0 - success_prob)/2.0\n x, y = goal\n value = [[collision_cost for _ in row] for row in grid]\n value[x][y] = 0\n policy = [[' ' for _ in row] for row in grid]\n policy[x][y] = '*'\n changed = True\n while (changed):\n changed = False\n for x in range(len(grid)):\n for y in range(len(grid[x])):\n if (isValidCell(grid, x, y)):\n for i, char in enumerate(delta_name):\n x2 = x + delta[i][0]\n y2 = y + delta[i][1]\n if (isValidCell(grid, x2, y2)):\n v2 = success_prob * value[x2][y2] + cost_step\n for n in [-1, 1]:\n i2 = (i + n) % 4\n x2 = x + delta[i2][0]\n y2 = y + delta[i2][1]\n if (isValidCell(grid, x2, y2)):\n v2 += failure_prob * value[x2][y2]\n else:\n v2 += failure_prob * collision_cost\n if (v2 < value[x][y]):\n value[x][y] = v2\n policy[x][y] = char\n changed = True\n\n return value, policy\n\n# ---------------------------------------------\n# Use the code below to test your solution\n# ---------------------------------------------\n\n\ngrid = [[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 1, 1, 0]]\ngoal = [0, len(grid[0])-1] # Goal is in top right corner\ncost_step = 1\ncollision_cost = 1000\nsuccess_prob = 0.5\n\nvalue, policy = stochastic_value(\n grid, goal, cost_step, collision_cost, success_prob)\nfor row in value:\n print(row)\nfor row in policy:\n print(row)\n\n# Expected outputs:\n#\n# [471.9397246855924, 274.85364957758316, 161.5599867065471, 0],\n# [334.05159958720344, 230.9574434590965, 183.69314862430264, 176.69517762501977],\n# [398.3517867450282, 277.5898270101976, 246.09263437756917, 335.3944132514738],\n# [700.1758933725141, 1000, 1000, 668.697206625737]\n\n\n#\n# ['>', 'v', 'v', '*']\n# ['>', '>', '^', '<']\n# ['>', '^', '^', '<']\n# ['^', ' ', ' ', '^']\n","repo_name":"ipujol10/artificialInteligengeforRobots","sub_path":"src/problemSet4.py","file_name":"problemSet4.py","file_ext":"py","file_size_in_byte":3720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"18235396470","text":"from random import randrange\nfrom aiogram.utils.markdown import link\n\n\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\nfrom aiogram.dispatcher.filters import Text\nfrom aiogram import types\nfrom aiogram import dispatcher\nfrom aiogram.utils.markdown import hide_link\n\nfrom dispatcher import dp, bot\nimport config\nimport re\nfrom keyboards.client_kb import kb_inAnk, kb_fromAnk, kb_lookAnk, kb_sogl, urlkb\nfrom bot import BotDB\nimport json\nimport string\n\n\nlastank = 0\n\nclass FSMstart(StatesGroup):\n starting = State()\n helouing = State()\n\n# КЛАСС ДЛЯ СОСТОЯНИЯ РЕГИСТРАЦИИ АНКЕТЫ\nclass FSMreg(StatesGroup):\n name = State()\n age = State()\n photo = State()\n spheres = State()\n desqription = State()\n education = State()\n hobbie = State()\n\nclass FSMlike(StatesGroup):\n fLike = State()\n\nclass FSMlook(StatesGroup):\n looking = State()\n messaging = State()\n\n#@dp.message_handler(commands = \"pp\")\n#async def asd(message: types.Message):\n# await FSMlike.fLike.set()\n# await message.answer(\"Твоя анкета кому-то понравилась! \")\n# await message.answer(\"Анкета кого-то\", reply_markup=kb_inAnk)\n\n\n#@dp.message_handler(state=FSMlike.fLike)\n#async def getADS(message: types.Message, state: FSMlike):\n# if message.text == \"🤝\":\n# await message.answer(\"Хорошо пообщаться вам!(%s)\", message.from_user.full_name)\n# messageCap_template = \"\"\"Хорошо пообщаться вам! {name}\"\"\"\n# lastankasd = BotDB.getlastankin(message.from_user.id)\n# foruser = BotDB.getRecFrend(message.from_user.id, lastankasd)\n# messageCap = messageCap_template.format(name=message.from_user.full_name)\n# await bot.send_message(foruser, messageCap)\n#\n# if message.text == \"👎\":\n# await message.answer(\"Поищем ещё людей\")\n# await state.finish()\n# await FSMlook.looking.set()\n# await message.answer(\"Чья-то анкета\", reply_markup=kb_lookAnk)\n\n# ХЭНДЛЕР ДЛЯ ОТМЕНЫ\n@dp.message_handler(state=\"*\", commands = \"отмена\")\n@dp.message_handler(Text(equals='Отмена', ignore_case = True), state=\"*\")\nasync def cancelHandler(message: types.Message, state: FSMreg):\n curent_state = await state.get_state()\n if curent_state is None:\n return\n await state.finish()\n await message.reply(\"ОК\")\nasync def cancelHandler2(message: types.Message, state: FSMlike):\n curent_state = await state.get_state()\n if curent_state is None:\n return\n await state.finish()\n await message.reply(\"ОК\")\n\n@dp.message_handler(state=FSMlike.fLike)\n@dp.message_handler(Text(equals=\"🤝\"), state=FSMlook.looking)\n@dp.message_handler(Text(equals=\"👎\"), state=FSMlook.looking)\n@dp.message_handler(Text(equals=\"Смотреть анкеты\"), state=None)\nasync def lookAnks(message: types.Message):\n if message.text == \"🤝\":\n lastankasd = BotDB.getlastankin(message.from_user.id)\n if(not BotDB.getfrengrecuest(lastankasd, message.from_user.id)):\n #метод для добавления\n\n feta = BotDB.tofriend(message.from_user.id, lastankasd)\n\n name = feta [2]\n age = feta [3]\n spheres = feta [4]\n desqription = feta [5]\n photo = feta [6]\n education = feta [8]\n hobbie = feta [9]\n messageCap_template = \"\"\"{name}, {age}\\nHard skills: {spheres}\\nSoft skills: {desqription}\\nОбразование: {education}\\nХобби: {hobbie}\"\"\"\n messageCap = messageCap_template.format(name=name, age=age, spheres=spheres, desqription=desqription, education=education, hobbie=hobbie)\n\n\n tsel_user = BotDB.unget_user_id(lastankasd)\n await bot.send_message(tsel_user, \"Твоя анкета кому-то понравилась!\")\n\n state = dp.current_state(chat=tsel_user, user=tsel_user)\n await state.set_state(FSMlook.looking)\n\n\n try:\n await bot.send_photo(tsel_user, photo, messageCap, reply_markup=kb_inAnk)\n except:\n print(\"не робит фото\")\n try:\n await bot.send_video(tsel_user, photo, caption = messageCap, reply_markup=kb_inAnk)\n except:\n print(\"не робит видео\")\n\n BotDB.setlastankin(BotDB.unget_user_id(lastankasd), BotDB.get_user_id(message.from_user.id))\n\n await message.reply('Предложение дружить отправлено\\nЖдите ответа')\n else:\n #добавление в др\n await message.answer(\"Ваше желание дружить взаимно!\")\n messageCap = hide_link('tg://user?id=753623377')\n\n #messageCap_template = 'Имя'\n #messageCap = messageCap_template.format(user_id = BotDB.unget_user_id(lastankasd))\n messageCap_template = '@{username}'\n messageCap = messageCap_template.format(username = BotDB.getUser_name(lastankasd))\n\n await message.answer(messageCap)\n await message.answer('Хорошо пообщаться вам!')\n #messageCap_template = \"\"\"Хорошо пообщаться вам! {name}\"\"\"\n BotDB.getRecFrend(message.from_user.id, lastankasd)\n #messageCap = messageCap_template.format(name=message.from_user.full_name)\n #await bot.send_message(foruser, messageCap)\n\n await FSMlook.looking.set()\n\n feta = BotDB.finf_ank(message.from_user.id, message)\n long = len(feta)\n ank = randrange(0, long)\n\n BotDB.setlastankin(message.from_user.id, feta[ank][1])\n name = feta [ank][2]\n age = feta [ank][3]\n spheres = feta [ank][4]\n desqription = feta [ank][5]\n photo = feta [ank][6]\n education = feta [ank][8]\n hobbie = feta [ank][9]\n\n\n messageCap_template = \"\"\"{name}, {age}\\nHard skills: {spheres}\\nSoft skills: {desqription}\\nОбразование: {education}\\nХобби: {hobbie}\"\"\"\n messageCap = messageCap_template.format(name=name, age=age, spheres=spheres, desqription=desqription, education=education, hobbie=hobbie)\n\n try:\n await bot.send_photo(message.from_user.id, photo, messageCap, reply_markup=kb_lookAnk)\n except:\n print(\"не робит фото\")\n try:\n await bot.send_video(message.from_user.id, photo, caption = messageCap, reply_markup=kb_lookAnk)\n except:\n print(\"не робит видео\")\n\n\n\n#@dp.message_handler(Text(equals=\"💌\"), state=FSMlook.looking)\n#async def looPerskAnk(message: types.Message, state: FSMlook):\n# await message.reply('Напишите сообщение для пользователя', reply_markup=None)\n# await FSMlook.next()\n\n\n\n#@dp.message_handler(state=FSMlook.messaging)\n#async def read(message: types.Message):\n# if {i.lower().translate(str.maketrans('','',string.punctuation)) for i in message.text.split(' ')} \\\n# .intersection(set(json.load(open('NL/nl.json')))) != set():\n# await message.reply('Маты запрещены!')\n# await message.delete()\n# else:\n# await message.reply('Сообщение отправлено\\nЖдите ответа')\n# await FSMlook.looking.set()\n# await message.answer(\"Чья-то анкета\", reply_markup=kb_lookAnk)\n\n\n#@dp.message_handler(Text(equals=\"👎\"), state=FSMlook.looking)\n#async def looPerskAnk(message: types.Message, state=FSMlook):\n# #Следущая анкета\n# await message.answer(\"Чья-то анкета\", reply_markup=kb_lookAnk)\n\n@dp.message_handler(Text(equals=\"💤\"), state=FSMlook.looking)\nasync def looPerskAnk(message: types.Message, state=FSMlook):\n await message.answer(\"Твоя анкета выглядит вот так:\", reply_markup=kb_fromAnk)\n try:\n await BotDB.get_ank(message.from_user.id, message)\n except:\n print(\"не робит фото\")\n try:\n await BotDB.get_ankv(message.from_user.id, message)\n except:\n print(\"не робит видео\")\n await state.finish()\n\n\n# ХЭНДЛЕРЫ ДЛЯ СОСТОЯНИЯ РЕГИСТРАЦИИ АНКЕТЫ\n@dp.message_handler(Text(equals=\"Заполнить анкету заново\"), state=None)\nasync def st(message: types.Message):\n await FSMreg.name.set()\n await message.answer(\"Как тебя зовут?\")\n\n@dp.message_handler(state=FSMreg.name)\nasync def getName(message: types.Message, state: FSMreg):\n async with state.proxy() as data:\n data['name'] = message.text\n await FSMreg.next()\n await message.answer(\"Сколько тебе лет?\")\n\n@dp.message_handler(state=FSMreg.age)\nasync def getAge(message: types.Message, state: FSMreg):\n try:\n if int(message.text) < 16:\n await message.answer(\"Тебе должно быть больше 16-ти лет\")\n if int(message.text) > 122:\n await message.answer(\"Тебе не может быть больше лет, чем старейшим из когда-либо живших на Земле людей!\")\n else:\n if int(message.text) >= 16:\n async with state.proxy() as data:\n data['age'] = message.text\n await FSMreg.next()\n await message.answer(\"Пришли своё фото или видео\")\n except:\n await message.answer(\"Введи пожалуйста корректный возраст\")\n\n@dp.message_handler(content_types=['video'], state=FSMreg.photo)\nasync def getPhoto(message: types.Message, state: FSMreg):\n async with state.proxy() as data:\n data['photo'] = message.video.file_id\n await FSMreg.next()\n await message.answer(\"Напиши, что ты умеешь? (hard skills)\")\n\n\n@dp.message_handler(content_types=['photo'], state=FSMreg.photo)\nasync def getPhoto(message: types.Message, state: FSMreg):\n async with state.proxy() as data:\n data['photo'] = message.photo[0].file_id\n await FSMreg.next()\n await message.answer(\"Напиши, что ты умеешь? (hard skills)\")\n\n@dp.message_handler(state=FSMreg.photo)\nasync def getPhoto(message: types.Message, state: FSMreg):\n await message.answer(\"Отправь \")\n\n\n@dp.message_handler(state=FSMreg.spheres)\nasync def getSpheres(message: types.Message, state: FSMreg):\n async with state.proxy() as data:\n data['spheres'] = message.text\n await FSMreg.next()\n await message.answer(\"Расскажи о своих Soft skills\")\n\n\n\n\n\n\n@dp.message_handler(state=FSMreg.desqription)\nasync def getDesqr(message: types.Message, state: FSMreg):\n mesamesa = message\n async with state.proxy() as data:\n data['desqription'] = message.text\n await FSMreg.next()\n await message.answer(\"Какой твой уровень образования?\")\n\n\n@dp.message_handler(state=FSMreg.education)\nasync def getSpheres(message: types.Message, state: FSMreg):\n async with state.proxy() as data:\n data['education'] = message.text\n await FSMreg.next()\n await message.answer(\"Какие твои хобби и интересы?\")\n\n\n@dp.message_handler(state=FSMreg.hobbie)\nasync def getSpheres(message: types.Message, state: FSMreg):\n async with state.proxy() as data:\n data['hobbie'] = message.text\n\n await message.answer(\"Твоя анкета выглядит вот так:\")\n #await message.answer(data['name'], data['age'], data['spheres'], data['desqription'])\n #await message.answer(\"Имя\", data['name'], \", \", data['age'], \" лет. \\n \", data['spheres'], \"\\n\", data['desqription'])\n BotDB.add_record(message.from_user.id, data['name'], data['age'], data['spheres'], data['desqription'], data['photo'],data['education'],data['hobbie'] )\n name = data['name']\n age = data['age']\n spheres = data['spheres']\n desqription = data['desqription']\n education = data['education']\n hobbie = data['hobbie']\n messageCap_template = \"\"\"{name}, {age}\\nHard skills: {spheres}\\nSoft skills: {desqription}\\nОбразование: {education}\\nХобби: {hobbie}\"\"\"\n messageCap = messageCap_template.format(name=name, age=age, spheres=spheres, desqription=desqription, education=education, hobbie=hobbie)\n\n try:\n await bot.send_photo(message.from_user.id, data['photo'], messageCap)\n except:\n print(\"не робит фото\")\n try:\n await bot.send_video(message.from_user.id, data['photo'], caption = messageCap)\n except:\n print(\"не робит видео\")\n\n\n await message.answer(\"В режиме просмотра анкет, вам будут доступны следущие реакции: \\n 🤝 - антека пользователя вам понравилась \\n 👎 - пропустить анкету пользователя \\n 💤 - выйти из просмотра анкет\", reply_markup=kb_fromAnk)\n await state.finish()\n\n\n\n\n# ХЭНДЛЕР СТАРТА\n@dp.message_handler(commands = \"start\")\nasync def helouing(message: types.Message):\n await FSMstart.starting.set()\n if(not BotDB.user_exists(message.from_user.id)):\n BotDB.add_user(message.from_user.id)\n\n await message.bot.send_message(message.from_user.id, \"Добро пожаловать! Я умный бот написанный на Python. \"\n \"Моя цель - свести тебя с нужными людьми.\", reply_markup=kb_sogl)\n await message.answer(\"Для начала, тебе необходимо принять пользовательское соглашение\", reply_markup=urlkb)\n await FSMstart.next()\n\n@dp.message_handler(Text(equals=\"Принять пользовательское соглашение\"),state=FSMstart.helouing)\nasync def start(message: types.Message, state = FSMstart):\n chat_id = message.from_user.username\n BotDB.user_take_polici(message.from_user.id, chat_id)\n await state.finish()\n await FSMreg.name.set()\n await message.answer(\"Теперь, давай познакомимся!\\nКак тебя зовут?\")\n\n# ХЭНДЛЕР ЛЮБОГО ВВОДА\n@dp.message_handler()\nasync def read(message: types.Message):\n if {i.lower().translate(str.maketrans('','',string.punctuation)) for i in message.text.split(' ')}\\\n .intersection(set(json.load(open('NL/nl.json')))) != set():\n await message.reply('Маты запрещены!')\n await message.delete()\n\n","repo_name":"kojimankix/StudFriend","sub_path":"Bot/handlers/personal_actions.py","file_name":"personal_actions.py","file_ext":"py","file_size_in_byte":14732,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"42918473322","text":"'''\nN개의 정수에서 이웃한 두 수의 합이 최대인 경우와 최소인 경우를 찾아 출력하시오. 예를 들어 5개의 정수 3 2 1 4 5의 경우, 이웃한 수의 합은 5, 3, 5, 9이므로 이중 최대와 최소인 9, 3을 출력한다.\n\n입력\n\n첫 줄에 테스트케이스 T, 다음 줄부터 테스트케이스 별로 첫 줄에 N, 다음 줄에 절대값10억 이하의 정수 N개가 빈 칸으로 구분되어 주어진다.\n\n1<=T<=10, 5<=N<=1000\n'''\n\ntest_case = int(input())\n\nfor tc in range(1, test_case+1):\n N = int(input())\n num_list = list(map(int, input().split()))\n max_num = -2000000000\n min_num = 2000000000\n \n for i in range(N-1):\n sum_num = num_list[i] + num_list[i+1]\n if sum_num > max_num:\n max_num = sum_num\n if sum_num < min_num:\n min_num = sum_num\n \n print(f'#{tc} {max_num} {min_num}')","repo_name":"song7351/TIL-algorithm","sub_path":"추가문제/10564_이웃한_수의_합.py","file_name":"10564_이웃한_수의_합.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"85"} +{"seq_id":"15354376877","text":"cluster_labels_copyright = 'cluster_weather_labels.py Copyright (c) 2020-2023 Scott L. Williams, released under GNU GPL V3.0'\n\n# poli batch implementation to train SOM and writes out labels\n# this version of SOM training is used to cluster pixels with similar labels\n\nimport os\nimport sys\nimport getopt\n\nimport numpy as np\n\nfrom npy_source_pack import npy_source\nfrom msom_pack import msom\nfrom render_pack import render\n\nnclasses = 25 # must match classes in SOM map (eg. *.labels)\n\n# instantiate the operators\n\n# numpy source\nsrc = npy_source.npy_source( 'npy_source' )\n\n# mini-som\nms = msom.msom( 'msom' )\nms.params.shape = (3,4) # net grid shape (3,4) \nms.params.sigma = 2\nms.params.nepochs = 30 # determines how many samples\n # should be considered. an epoch\n # is a full samping of the data.\n # multiples epochs allow for pixel\n # reconsideration and node reassigment.\n \nms.params.thresh = None # set to stop processing below this value\n # set low to see QE values per epoch\n # otherwise set to None\n\nms.params.rate = 0.3 # 0.5 for jan-mar_2019 for decay 3\nms.params.init_weights = 'pca'\nms.params.neighborhood_function = 'gaussian'\nms.params.topology = 'hexagonal'\nms.params.activation_distance = 'euclidean'\nms.params.output_type = 'labels'\nms.params.apply_classification = True\nms.params.seed = None\nms.params.rorder = True\nms.params.order_by_size = False\nms.params.decay_function = 4 # linear decay function; was 3 for jan-mar_2019 with nepochs=50\nms.params.calc_epoch_QE = True\n\n# render labels as image\nrndr = render.render( 'render' )\nrndr.readlut( './luts/sixteenthbow.lut' )\n\n# -----------------------------------------------------------\n\ndef cluster( infile, outdir ) :\n\n print( 'output directory for clustering:', outdir,\n file=sys.stderr, flush=True )\n \n # read the daily labels file as training data\n print( 'reading datafile: ' + infile + '...',\n file=sys.stderr, flush=True, end='' )\n src.params.filepath = infile\n src.run()\n print( 'done', file=sys.stderr, flush=True )\n\n print( 'number of epochs=', ms.params.nepochs, file=sys.stderr, flush=True )\n print( 'learning rate=', ms.params.rate, file=sys.stderr, flush=True )\n\n # for each pixel make a label histogram, use this as a feature vector\n print( 'making histograms...', file=sys.stderr, flush=True, end='' )\n height, width, nbins = src.sink.shape\n hist = np.empty( (height,width,nclasses), dtype=np.int64 )\n\n # construct an image of histograms and cluster these\n for j in range( height ):\n for i in range( width ):\n\n # for each pixel make a histogram of labels\n h,b = np.histogram( src.sink[j,i,:], bins=nclasses,\n range=(0.0,float(nclasses-1)) )\n hist[j,i,:] = h\n\n # NOTE: if you get this error:\n # minisom.py:486: RuntimeWarning: invalid value encountered in sqrt\n # return sqrt(-2 * cross_term + input_data_sq + weights_flat_sq.T)\n # it is saying that the data type cannot fit the result a square operation.\n # eg, dtype=uint16 but 364*364=132496 which is bigger than 2^16 - 1 = 65535\n\n\n print( 'done', file=sys.stderr, flush=True )\n\n ''' \n # report max and min\n mx = np.amax( hist )\n mn = np.amin( hist )\n print( mx, mn, file=sys.stderr, flush=True )\n ''' \n \n # rational for not normalizing: feature vector components\n # have same units, ie. number of days\n\n # make numpy file for graphics\n hist.dump( outdir + '/hist.npy' )\n\n # link output to msom input and run\n print( 'training ...', file=sys.stderr, flush=True )\n\n ms.params.mapfile_prefix = outdir + '/cluster'\n ms.source = hist\n ms.run() # train\n\n # save the cluster labels\n ms.sink.dump( outdir + '/cluster.npy' )\n\n # render as image\n rndr.params.filepath = outdir + '/cluster.jpg'\n rndr.source = ms.sink\n rndr.run()\n\n# ---------------------------------------------------------------\n\n\ndef usage( self ):\n print( 'usage: cluster_labels.py', file=sys.stderr )\n print( ' -h, --help', file=sys.stderr )\n print( ' -i datafile --input=datafile', file=sys.stderr )\n print( ' -o outdir, --outdir=outdir',file=sys.stderr )\n \ndef get_params( argv ):\n datafile = None\n outdir = None\n \n try: \n opts, args = getopt.getopt( argv, 'hi:o:',\n ['help','input=','outdir='] )\n \n except getopt.GetoptError: \n self.usage() \n sys.exit(2) \n \n for opt, arg in opts: \n if opt in ( '-h', '--help' ): \n self.usage() \n sys.exit(0)\n elif opt in ( '-i', '--input' ):\n datafile = arg\n elif opt in ( '-o', '--outdir' ):\n outdir = arg\n else:\n self.usage() \n sys.exit(1)\n\n if datafile == None:\n print( 'cluster_labels: datafile is missing...exiting' )\n sys.exit(1)\n if outdir == None:\n print( 'cluster_labels: outdir is missing...exiting' )\n sys.exit(1)\n\n return datafile, outdir\n\n####################################################################\n# command line user entry point \n####################################################################\nif __name__ == '__main__': \n\n dataf,outd = get_params( sys.argv[1:] )\n print( dataf, outd )\n cluster( dataf, outd )\n","repo_name":"yachaytech/eto_climate_1D","sub_path":"cluster_weather_labels.py","file_name":"cluster_weather_labels.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"41178697158","text":"\nfrom pandas import read_excel\nfrom os.path import join, exists\nfrom subprocess import call\n\nENG_JOBS = r\"\\\\hssieng\\DATA\\HS\\JOBS\"\nFLG_DATA_EXEC = r\"\\\\hssieng\\Resources\\HS\\PROG\\FlgXlsData.exe\"\n\n\nclass FlangeData:\n\n def __init__(self, job):\n self.job = job\n\n self.flg_data_file = join(ENG_JOBS, self.job, 'CAM', 'FlangeData.xlsx')\n if not exists(flg_data_file):\n self.generate_flg_data()\n\n self.get_data()\n\n def get_data(self, ):\n self.data = read_excel(self.flg_data_file)\n\n def generate_flg_data(self):\n call([FLG_DATA_EXEC, self.job])\n","repo_name":"paddymills/prodctrlcore","sub_path":"src/prodctrlcore/hssformats/flgdata.py","file_name":"flgdata.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"29738775450","text":"print('Informe a altura e genero de 15 pessoas: \\n')\r\nqtn_mulher = 0\r\nqtn_homem = 0\r\nmaior_altura = None\r\nmenor_altura = None\r\ntot_altura = 0\r\n\r\nfor i in range(15):\r\n altura = float(input(f'Informe a aultura da pessoa {i + 1}: '))\r\n genero = input(f'Informe o gênero da pessoa {i + 1}(M/F): ')\r\n print('=============================================')\r\n\r\n if genero.lower() == 'f':\r\n qtn_mulher += 1\r\n if genero.lower() == 'm':\r\n qtn_homem += 1\r\n tot_altura += altura\r\n if maior_altura == None or altura > maior_altura:\r\n maior_altura = altura\r\n if menor_altura == None or altura < menor_altura:\r\n menor_altura = altura\r\n\r\n\r\nmedia = tot_altura / qtn_homem\r\n\r\nprint(media)\r\nprint(qtn_mulher)\r\nprint(maior_altura)\r\nprint(menor_altura)","repo_name":"BrunoPFmaia/Front-End-II_Uniesp","sub_path":"nivelamento_p2b.py","file_name":"nivelamento_p2b.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"32898581092","text":"# BFS\nimport collections\n\n\n# def bfs(graph, root):\n# seen, queue = set([]), collections.deque([root])\n# while queue:\n# current = queue.popleft()\n# if current not in seen:\n# seen.add(current)\n# for node in graph[current]:\n# queue.append(node)\n#\n# graph = {1: [2, 3], 2: [4, 5], 3: [6], 4: [], 5: [6], 6: [7], 7: [5]}\n# print(bfs(graph, 1))\n\n\ndef maze(graph):\n main = {}\n paths, root = [], ()\n for idx_r, row in enumerate(graph):\n for idx_e, element in enumerate(row):\n if element == ' ':\n paths.append((idx_r, idx_e))\n elif element == 'X':\n paths.append((idx_r, idx_e))\n root = (idx_r, idx_e)\n for node in paths:\n if node not in main:\n main[node] = set([])\n for _node in paths:\n if (node[0] == _node[0] and _node[1] in (node[1] - 1, node[1] + 1)) or\\\n (node[1] == _node[1] and _node[0] in (node[0] - 1, node[0] + 1)):\n main[node].add(_node)\n nearest_exit = find_nearest_exit(graph, root, paths)\n if nearest_exit:\n return draw_path_in_maze(main, root, nearest_exit, graph)\n return \"There is no exit from this position.\"\n\n\ndef draw_path_in_maze(graph, root, exit, maze):\n queue = [(root, [root])]\n result = []\n while queue:\n (current, path) = queue.pop(0)\n for node in graph[(current)] - set(path):\n if list(node) == exit:\n result = path + [node]\n else:\n queue.append((node, path + [node]))\n maze_with_path = []\n for idx_r, row in enumerate(maze):\n _row = []\n for idx_e, element in enumerate(row):\n if element == ' ':\n if (idx_r, idx_e) in result:\n _row.append('.')\n else:\n _row.append(element)\n else:\n _row.append(element)\n maze_with_path.append(''.join(_row))\n return ''.join([row + '\\n' for row in maze_with_path])\n\n\ndef find_nearest_exit(graph, root, paths):\n seen, queue = set([]), collections.deque([root])\n while queue:\n current = queue.popleft()\n row = current[0]\n position = current[1]\n if (row in [0, len(graph) - 1] or position in [0, len(graph[0]) - 1])\\\n and row != root[0] and position != root[1]:\n print(\"The coordinates of nearest exit are: [{}, {}]\".format(row, position))\n return [row, position]\n if current not in seen:\n seen.add(current)\n for node in paths:\n if node[0] == row and node[1] in [position + 1, position - 1]:\n queue.append(node)\n if node[1] == position and node[0] in [row + 1, row - 1]:\n queue.append(node)\n\n\ngraph = [\n '#X###############',\n '# # # # #',\n '# # #### # # ####',\n '# # # # #',\n '### #### # # ## #',\n '# # # #',\n '########## ######',\n '# # ######',\n '###### ### #',\n '# ## # #',\n '### ######### ###',\n '# # ## #',\n '### ########### #',\n '# # #',\n '# ######## ## ###',\n '# ### # ## ###',\n '#### ## ## #',\n '## # #### ##### #',\n '# # # #',\n '# ## # #### ### #',\n '# # ###### #',\n '# #### # # ###',\n '# ### ########',\n '## ##############',\n]\n\n\ndef path_finder(area):\n splitted_area = area.splitlines()\n end = height, width = len(splitted_area) - 1, len(splitted_area[0]) - 1\n queue, seen, path = {(0, 0): 0}, set(), []\n while queue:\n x, y = min(queue, key=queue.get)\n total_path_weight = queue.pop((x, y))\n seen.add((x, y))\n if (x, y) == end:\n # path.append(end)\n # return path_drawer(area, width, path)\n return total_path_weight\n for i, j in (-1, 0), (1, 0), (0, -1), (0, 1):\n z, w = x + i, y + j\n if (z, w) in seen or not (0 <= z <= height and 0 <= w <= width):\n continue\n single_path_weight = total_path_weight + abs(int(splitted_area[x][y]) - int(splitted_area[z][w]))\n if single_path_weight < queue.get((z, w), float('inf')):\n queue[z, w] = single_path_weight\n # if (x, y) not in path: path.append((x, y))\n\n\ndef path_drawer(area, width, path):\n splitted_area = area.splitlines()\n area_with_path = []\n for idx_row, row in enumerate(splitted_area):\n counter = 0\n for idx_col, col in enumerate(row):\n counter += 1\n if (idx_row, idx_col) in path:\n area_with_path.append('*')\n else:\n area_with_path.append(col)\n if counter == width + 1:\n area_with_path.append('\\n')\n return ''.join(area_with_path)\n\n\narea = '\\n'.join([\n '000000000000000000',\n '111111111111111110',\n '000000000000000000',\n '011111111111111111',\n '000000000000000000',\n '111111111111111110',\n '000000000000000000',\n '111111111111111110',\n '000000000000000000',\n '011111111111111111',\n '000000000000000000',\n '111111111111111110',\n '000000000000000000',\n '111111111111111110',\n '000000000000000000',\n '011111111111111111',\n '000000000000000000',\n '111111111111111110',\n])\n","repo_name":"TTomasik/python_practice","sub_path":"algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33517730489","text":"lista=list()\n\nwhile True:\n\tnombre=input(\"Introduce nombre\\n\")\n\tingrediente=input(\"Introduce ingrediente principal\\n\")\n\tcalorias=input(\"Introduce calorias\\n\")\n\tdificultad=input(\"Introduce dificultad\\n\")\n\texplicacion=input(\"Introduce explicacion\\n\")\n\tlista.append([nombre,ingrediente,calorias,dificultad,explicacion])\n\n\tif len(lista)>1:\n\t\tbreak\n\nfor i in lista:\n for j in i:\n print(j)\n\n\na=int(input(\"dime que numero de receta quieres eliminar: \"))\nif a==1:\n print (lista[1])\nelif a==2:\n print (lista[0])\nelse:\n print(\"no elimino ninguna, no se que dices\")\n\n\nnreceta=input(\"dime el nombre de la receta: \")\nrecetar=list()\nf=False\n\nfor receta in lista:\n for dato in receta:\n if nreceta==dato:\n recetar=receta\n f=True\nif f:\n print(recetar)\nelse:\n print(\"No lo he encoontrado\")\n\n# He hecho el \"Actualizar un element\" :)\nwhile True:\n v=input(\"¿Quieres actualizar alguna de las recetas?: \")\n if v == \"si\":\n l = int(input(\" ¿Cual de las dos recetas quieres cambiar?: \"))\n k = int(input(\"¿Que elemento de la lista quieres cambiar?: \"))\n p = input(\"Que es lo que quieres intercambiar: \")\n lista[l-1][k-1] = p\n print(lista)\n break\n elif v==\"no\":\n print(\"Muy bien, adios\")\n else:\n print(\"no se que quieres decir\")\n continue","repo_name":"AdriGeaPY/programas1ava","sub_path":"zprimero/Examenes/4examen.py","file_name":"4examen.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"33972515245","text":"class Solution(object):\n def __init__(self):\n self.memory = {}\n\n def fib(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n\n if n in self.memory:\n return self.memory[n]\n if n <= 1:\n return n\n\n result = int((self.fib(n-1) + self.fib(n-2)) % (1e9+7))\n self.memory[n] = result\n return result\n\n # 矩阵快速幂\n def fib2(self, n):\n MOD = 10 ** 9 + 7\n if n < 2:\n return n\n\n def multiply(a, b):\n c = [[0, 0], [0, 0]]\n for i in range(2):\n for j in range(2):\n c[i][j] = (a[i][0] * b[0][j] + a[i][1] * b[1][j]) % MOD\n \n return c\n\n def matrix_pow(a, n):\n ret = [[1, 0], [0, 1]]\n while n > 0:\n if n & 1:\n ret = multiply(ret, a)\n n >>= 1\n a = multiply(a, a)\n return ret\n\n res = matrix_pow([[1, 1], [1, 0]], n - 1)\n return res[0][0]\n","repo_name":"xuychen/Leetcode","sub_path":"LCOF/1-10/10-1/10-1.py","file_name":"10-1.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"1250042529","text":"from csp import CSP\n\ncsp_instance = CSP(\n var_domains = {'a' : {1,2},\n 'b' : {1,2},\n 'c' : {3,4},\n 'd' : {1,2,3,4}\n },\n constraints = {\n lambda a, b: a >= b,\n lambda a, b: b >= a,\n lambda a, b, c: c > a + b,\n lambda d: d <= d,\n }\n)\n\nassert type(csp_instance) is CSP\nprint(sorted(csp_instance.var_domains.keys()))\nprint(len(csp_instance.constraints))","repo_name":"Loquaxious/COSC367","sub_path":"ExamRevision/Exam 2020/q7_csp_arc_consistent.py","file_name":"q7_csp_arc_consistent.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"929069131","text":"import torch\n\n\ndef rand_bbox(size, lam):\n W, H = size\n cut_rat = (1. - lam).sqrt()\n cut_w = (W * cut_rat).to(torch.long)\n cut_h = (H * cut_rat).to(torch.long)\n\n cx = torch.zeros_like(cut_w, dtype=cut_w.dtype).random_(0, W)\n cy = torch.zeros_like(cut_h, dtype=cut_h.dtype).random_(0, H)\n\n bbx1 = (cx - cut_w // 2).clamp(0, W)\n bby1 = (cy - cut_h // 2).clamp(0, H)\n bbx2 = (cx + cut_w // 2).clamp(0, W)\n bby2 = (cy + cut_h // 2).clamp(0, H)\n\n new_lam = 1. - (bbx2 - bbx1).to(lam.dtype) * (bby2 - bby1).to(lam.dtype) / (W * H)\n\n return (bbx1, bby1, bbx2, bby2), new_lam\n\n\ndef cutmix(input, alpha):\n beta = torch.distributions.beta.Beta(alpha, alpha)\n randind = torch.randperm(input.shape[0], device=input.device)\n lam = beta.sample().to(device=input.device)\n lam = torch.max(lam, 1. - lam)\n (bbx1, bby1, bbx2, bby2), lam = rand_bbox(input.shape[-2:], lam)\n output = input.clone()\n output[..., bbx1:bbx2, bby1:bby2] = output[randind][..., bbx1:bbx2, bby1:bby2]\n return output, randind, lam\n","repo_name":"alinlab/object-aware-contrastive","sub_path":"models/cutmix.py","file_name":"cutmix.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"85"} +{"seq_id":"22569242189","text":"import pytest\n\nfrom solution import number_of_pairs\n\n\nbasic_tests = [\n ([\"red\", \"red\"], 1),\n ([\"red\", \"green\", \"blue\"], 0),\n ([\"gray\", \"black\", \"purple\", \"purple\", \"gray\", \"black\"], 3),\n ([], 0),\n ([\"red\", \"green\", \"blue\", \"blue\", \"red\", \"green\", \"red\", \"red\", \"red\"], 4),\n]\n\n\n@pytest.mark.parametrize(\n \"gloves, expected\", basic_tests\n)\ndef test_should_count_number_of_pairs_for_basic_tests(gloves, expected):\n assert number_of_pairs(gloves) == expected\n","repo_name":"estraviz/codewars","sub_path":"6_kyu/Pair of gloves/python/test_solution.py","file_name":"test_solution.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"85"} +{"seq_id":"70518586518","text":"#!/usr/bin/env python3\n\"\"\"\nRepresenting poisson distribution\n\"\"\"\n\n\nclass Poisson:\n \"\"\"\n Class poisson distribution\n \"\"\"\n e = 2.7182818285\n\n def __init__(self, data=None, lambtha=1.):\n \"\"\"\n Class contructor\n \"\"\"\n if data is None:\n if lambtha <= 0:\n raise ValueError(\"lambtha must be a positive value\")\n else:\n self.lambtha = float(lambtha)\n else:\n if type(data) is not list:\n raise TypeError(\"data must be a list\")\n if len(data) < 2:\n raise ValueError(\"data must contain multiple values\")\n self.lambtha = sum(data) / len(data)\n\n def pmf(self, k):\n \"\"\"\n Probability Mass Function for poisson\n \"\"\"\n if type(k) is not int:\n k = int(k)\n if k < 0:\n return 0\n e_mean = Poisson.e ** - self.lambtha\n mean_k = self.lambtha ** k\n x_factorial = 1\n for i in range(1, k + 1):\n x_factorial *= i\n pmf = e_mean * mean_k / x_factorial\n return pmf\n\n def cdf(self, k):\n \"\"\"\n Cumulative Distribution Function for poisson\n \"\"\"\n if type(k) is not int:\n k = int(k)\n if k < 0:\n return 0\n cdf = 0\n for i in range(k + 1):\n cdf += Poisson.pmf(self, i)\n return cdf\n","repo_name":"Kenneth-ca/holbertonschool-machine_learning","sub_path":"math/0x03-probability/poisson.py","file_name":"poisson.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"85"} +{"seq_id":"10623578730","text":"\"\"\"\nQuantitative table generation\n\"\"\"\n\nfrom math import ceil, log10\nfrom numbers import Real\nfrom typing import Dict, List, Tuple\n\nfrom numpy import arange\nfrom pandas import DataFrame, Series\n\nfrom marco.frecuency_table import frecuency_table\nfrom marco.grouped_frame import GroupedFrame\nfrom marco.quantitative_frame import QuantitativeFrame\nfrom marco.ungrouped_frame import UngroupedFrame\n\nQuantitativeClass = List[Tuple[Real, Real]]\n\n\ndef quantitative_table(data: List[Real]) -> QuantitativeFrame:\n \"\"\"Generate a QuantitativeFrame depending on the data size\"\"\"\n if len(data) > 20:\n return generate_grouped_table(data)\n return generate_ungrouped_table(sorted(data))\n\n\ndef generate_grouped_table(data: List[Real]) -> GroupedFrame:\n \"\"\"Generates a GroupedFrame for data size more than 20 elements\"\"\"\n Ro = range_set(data)\n class_n = class_amount(len(data))\n fixed_data = apply_range_fix(data, Ro)\n interval_value = interval(Ro, class_n)\n q_class = quantitative_class(fixed_data, interval_value, class_n)\n mi = class_mark(q_class)\n ni = quantitative_absolute_frecuency(sorted(data), q_class)\n mi_x_ni = [a * b for a, b in zip(mi, ni.values())]\n\n relative_frecuency = [v / sum(ni.values()) for v in ni.values()]\n cumulative_relative = Series(relative_frecuency).cumsum()\n percentage_frequency = [i * 100 for i in relative_frecuency]\n\n return GroupedFrame(\n data,\n DataFrame(\n {\n \"Clase\": q_class,\n \"mi\": mi,\n \"ni\": ni.values(),\n \"Ni\": Series(ni.values()).cumsum().tolist(),\n \"hi\": relative_frecuency,\n \"Hi\": cumulative_relative,\n \"%\": percentage_frequency,\n \"% acum\": Series(percentage_frequency).cumsum().tolist(),\n \"mi x ni\": mi_x_ni,\n },\n ),\n interval_value\n )\n\n\ndef generate_ungrouped_table(data: List[Real]) -> UngroupedFrame:\n \"\"\"\n Generates a UngroupedFrame for the quantitative varibles when data size is up to 20\n \"\"\"\n return UngroupedFrame(data, frecuency_table(data))\n\n\ndef range_set(data: List[Real]) -> Real:\n \"\"\"Compute range set of a list of elements\"\"\"\n return max(data) - min(data)\n\n\ndef class_amount(data_amount: int) -> int:\n \"\"\"Compute class amount (k) of a data size\"\"\"\n return ceil(1 + 3.3 * log10(data_amount))\n\n\ndef interval(range_interval: Real, class_amount: int) -> int:\n \"\"\"Compute how wide is a data size\"\"\"\n return ceil(range_interval / class_amount)\n\n\ndef quantitative_class(\n data: List[Real], interval: int, class_amount: int\n) -> QuantitativeClass:\n \"\"\"Generates the classes from grouped data\"\"\"\n tuples_list = []\n lower_limit = data[0]\n for _ in range(class_amount):\n upper_limit = lower_limit + interval\n tuples_list.append((lower_limit, upper_limit))\n lower_limit += interval\n\n return tuples_list\n\n\ndef class_mark(quantitative_class: QuantitativeClass) -> List[Real]:\n \"\"\"Compute the class marks of each class in a quantitative class\"\"\"\n return [(q[0] + q[1]) / 2 for q in quantitative_class]\n\n\ndef fix_range(class_amount: int, interval: int, range_interval: Real) -> Real:\n \"\"\"Get the fix range of a data size\"\"\"\n return (class_amount * interval - range_interval) / 2\n\n\ndef apply_range_fix(data: List[Real], range_interval: Real) -> List[Real]:\n \"\"\"Get a new list with the corner elements' range fixed\"\"\"\n sorted_data = sorted(data)\n class_n = class_amount(len(data))\n interval_value = interval(range_interval, class_n)\n range_fix = fix_range(class_n, interval_value, range_interval)\n sorted_data[0] -= range_fix\n sorted_data[-1] += range_fix\n return sorted_data\n\n\ndef quantitative_absolute_frecuency(\n data: List[Real], q_class: QuantitativeClass\n) -> Dict[str, int]:\n \"\"\"Compute the absolute frecuency of a grouped data\"\"\"\n mapped = {str(clazz): 0 for clazz in q_class}\n i = j = 0\n\n while i < len(data):\n value = data[i]\n lower_limit = q_class[j][0]\n upper_limit = q_class[j][1]\n if value in arange(lower_limit, upper_limit, 0.5) or j >= len(q_class) - 1:\n mapped[str(q_class[j])] = mapped.get(str(q_class[j])) + 1\n i += 1\n else:\n if j < len(q_class) - 1:\n j += 1\n return mapped\n","repo_name":"upen-source/marco","sub_path":"marco/quantitative.py","file_name":"quantitative.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"18814900600","text":"from __future__ import print_function\nfrom __future__ import absolute_import\n\n# Communication to TensorFlow server via gRPC\nfrom grpc.beta import implementations\nimport tensorflow as tf\nimport cv2\nimport time\nimport numpy as np\nfrom PIL import Image\n# TensorFlow serving stuff to send messages\nfrom tensorflow_serving.apis import predict_pb2\nfrom tensorflow_serving.apis import prediction_service_pb2\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\n\n# Command line arguments\ntf.app.flags.DEFINE_string('server', 'localhost:9000',\n 'PredictionService host:port')\ntf.app.flags.DEFINE_string('image', '', 'path to image in JPEG format')\nFLAGS = tf.app.flags.FLAGS\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\ndef load_label_map(labels, num_classes):\n label_map = label_map_util.load_labelmap(labels)\n categories = label_map_util.convert_label_map_to_categories(label_map,\n\t\t\t\t\t\t\t max_num_classes=num_classes,\n\t\t\t\t\t\t\t use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n return category_index\n\n\ncategory_index = load_label_map('object_detection/data/pet_label_map.pbtxt', 37)\n\n\n\ndef main(_):\n host, port = FLAGS.server.split(':')\n channel = implementations.insecure_channel(host, int(port))\n stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)\n\n\n # Send request\n start_time = time.time()\n request = predict_pb2.PredictRequest()\n #image = Image.open(FLAGS.image)\n #image_np = load_image_into_numpy_array(image)\n #image_np_expanded = np.expand_dims(image_np, axis=0)\n\n image = cv2.imread(FLAGS.image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image, axis=0)\n print(image_np_expanded.shape)\n\n # Call model to make prediction on the image\n request.model_spec.name = 'faster_rcnn_resnet101_pets'\n request.model_spec.signature_name = 'serving_default'\n request.inputs['inputs'].CopyFrom(\n tf.contrib.util.make_tensor_proto(image_np_expanded, shape=image_np_expanded.shape, dtype='uint8'))\n\n result = stub.Predict(request, 60.0) # 60 secs timeout\n boxes = result.outputs['detection_boxes'].float_val\n classes = result.outputs['detection_classes'].float_val\n scores = result.outputs['detection_scores'].float_val\n print(\"cost %ss to predict: \" % (time.time() - start_time))\n #print(boxes) \n #print(classes)\n #print(scores)\n vis_util.visualize_boxes_and_labels_on_image_array(\n image,\n np.reshape(boxes,[300,4]),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n \n cv2.namedWindow(\"detection\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"detection\", image)\n cv2.waitKey(0)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"liangyanfeng/tf-serving","sub_path":"faster_rcnn_resnet101_pets_client.py","file_name":"faster_rcnn_resnet101_pets_client.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"38572482450","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on June 26 2018\n\n@author: kushal\n\nChatzigeorgiou Group\nSars International Centre for Marine Molecular Biology\n\nGNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007\n\n\"\"\"\n\nfrom .tab_page_pytemplate import *\nfrom .row import Row\nimport pandas as pd\nfrom functools import partial\nfrom typing import Union\n\n\nclass Page(QtWidgets.QWidget):\n def __init__(self, parent, stim_type: str):\n QtWidgets.QWidget.__init__(self)\n\n self.ui = Ui_TabPage()\n self.ui.setupUi(self)\n\n self.stim_type = stim_type\n self.rows = [] #: List of row objects, each row holds one stimulus period.\n self.ui.btnAddRow.clicked.connect(lambda: self.add_row())\n\n def set_data(self, dataframe: pd.DataFrame):\n \"\"\"\n Set the stimulus map\n\n :param dataframe: DataFrame with the appropriate rows (see add_row())\n \"\"\"\n self.clear()\n for ix, series in dataframe.iterrows():\n self.add_row(series)\n\n def get_dataframe(self) -> pd.DataFrame:\n \"\"\"\n Get the stimulus map as a DataFrame\n \"\"\"\n if len(self.rows) < 1:\n raise IndexError('No stimuli input for this stimulus type: ' + self.stim_type)\n\n l = []\n for row in self.rows:\n l.append(row.get_dict())\n return pd.DataFrame(l)\n\n def set_units(self, units: str):\n \"\"\"\n Set the time units\n\n :param units: One of 'frames' or 'seconds'\n \"\"\"\n\n if units not in ['frames', 'seconds']:\n raise ValueError('Units must be either \"frames\" or \"seconds\"')\n\n ix = self.ui.comboBoxTimeUnits.findText(units)\n self.ui.comboBoxTimeUnits.setCurrentIndex(ix)\n\n def get_units(self) -> str:\n \"\"\"\n Get the time units\n \"\"\"\n return self.ui.comboBoxTimeUnits.currentText()\n\n def add_row(self, pd_series: pd.Series = None):\n \"\"\"\n Add a row to the stimulus map\n\n :param pd_series: pandas series containing the following: stimulus name, start, end, and color\n :return:\n \"\"\"\n row = Row(pd_series)\n self.rows.append(row)\n row.btn_remove.clicked.connect(partial(self.delete_row, row))\n self.ui.verticalLayout.insertLayout(self.ui.verticalLayout.count() - 1, row.hlayout)\n\n def delete_row(self, row: Union[Row, int]):\n \"\"\"\n Delete a row from the stimulus map\n\n :param row: The Row object to remove or the numerical index of the row\n \"\"\"\n\n if isinstance(row, int):\n row = self.rows[row]\n if not isinstance(row, Row):\n raise TypeError(\"row must be either a Row object or int\")\n\n self.ui.verticalLayout.removeItem(row.hlayout)\n self.rows.remove(row)\n row.delete()\n row.hlayout.deleteLater()\n row.deleteLater()\n\n def clear(self):\n \"\"\"Clear the stimulus map\"\"\"\n while len(self.rows) > 0:\n self.delete_row(self.rows[0])\n\n def set_stim_autocompleter(self, stimulus_list: list):\n autocompleter = QtWidgets.QCompleter(stimulus_list)\n for row in self.rows:\n row.name.setCompleter(autocompleter)\n","repo_name":"kushalkolar/MESmerize","sub_path":"mesmerize/viewer/modules/stimmap_modules/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"80"} +{"seq_id":"3683133938","text":"\"\"\"\ncombination: abC -> AbC, aBC, abC, ABC.\nonly need lower case to upper case\noutput list of possibilities\n\"\"\"\n\n\"\"\"\n\\\\ backtracking\ncreat fun (list, idx):\n if idx == len(list) -1:\n append this sequence\n \n list[idx]-> upper case\n for i in range idx, last:\n if list[i] is lower case:\n backtracking(list add uppercase, i)\n \nfun(list, 0)\n\"\"\"\n\ndef UpperCombination(arr):\n if not arr: return []\n result = []\n\n def backtracking(idx, curlist):\n if len(curlist) == len(arr):\n result.append(curlist[:])\n print(\"curlist\",curlist)\n #\n for i in range(idx, len(arr)):\n # print(arr[i])\n if arr[i].islower():\n print(\"backtracking\", curlist + [arr[i].upper()])\n backtracking(i+1, curlist + [arr[i].upper()])\n\n backtracking(i + 1, curlist + [arr[i]])\n print(curlist)\n backtracking(0, [])\n\n return result\n\nprint(UpperCombination('abCd'))\n","repo_name":"Blossomyyh/leetcode","sub_path":"Pinterest/Combination.py","file_name":"Combination.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"8224236007","text":"class Node:\r\n def __init__(self, value):\r\n self.value = value\r\n self.next = None\r\n\r\nclass Stack:\r\n def __init__(self, value):\r\n new_node = Node(value)\r\n self.top = new_node\r\n self.heigth = 1\r\n\r\n def print_stack(self):\r\n temp = self.top\r\n while temp is not None:\r\n print(temp.value)\r\n temp = temp.next\r\n print('Bottom reached.\\n')\r\n\r\n def push(self, value):\r\n new_node = Node(value)\r\n new_node.next = self.top\r\n self.top = new_node\r\n self.heigth += 1\r\n return True\r\n\r\n def pop(self):\r\n if self.top == None:\r\n return False\r\n temp = self.top.next\r\n self.top.next = None\r\n self.top = temp\r\n self.heigth -= 1\r\n\r\nmy_stack = Stack(2)\r\nmy_stack.print_stack()\r\n\r\nmy_stack.push(1)\r\nmy_stack.push(0)\r\nmy_stack.push(-1)\r\nmy_stack.push(-2)\r\nmy_stack.print_stack()\r\n\r\nmy_stack.pop()\r\nmy_stack.pop()\r\nmy_stack.print_stack()","repo_name":"Kaan-ek/Data-structures-and-algorithms","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38849977469","text":"import cv2, scipy.misc, time\nfrom PIL import ImageGrab\nimport numpy as np\nfrom directkeys import *\n\n\ndef grab_screen():\n \n kernel = 5\n grayscreen = np.array(ImageGrab.grab(bbox=(0, 120, 1600, 1300)).convert('L'))\n grayscalesmooth = cv2.GaussianBlur(grayscreen, (kernel, kernel), 0)\n\n low_thresh = 100\n high_thresh = 200\n edge = cv2.Canny(grayscalesmooth, low_thresh, high_thresh)\n\n edge_image = scipy.misc.toimage(edge)\n\n return edge_image\n\n\nscreen_list = []\n\nfor i in range(10):\n # grab a screen capture every second for 10\n time.sleep(1)\n screen_list.append(grab_screen())\n\nfor im in screen_list:\n im.show()\n\nproject64_options = {\n 'left' : '0xCB',\n 'right' : '0xCD',\n 'up' : '0xC8',\n 'down' : '0xD0',\n 'delete' : '0xD3',\n 'pagedown' : '0xD1',\n 'pageup' : '0xC9',\n 'home' : '0xC7',\n 'end' : '0xCF',\n 'num4' : '0x4B',\n 'num6' : '0x4D',\n 'num8' : '0x48',\n 'num2' : '0x50',\n 'x' : '0x2D',\n 'c' : '0x2E',\n 'enter' : '0x1C',\n 'a' : '0x1E',\n 's' : '0x1F',\n 'z' : '0x2C'\n}","repo_name":"chrisnava07/Mario64","sub_path":"Mario_learnin.py","file_name":"Mario_learnin.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26813919573","text":"\"\"\"All constants pertaining to the StarbucksAutoma project\"\"\"\n\nimport pathlib\n\nfrom seleniumwire import webdriver\nfrom selenium.webdriver.firefox.options import Options\n\nfrom pyvirtualdisplay import Display\n\nPORTAL_URL = \"https://starbucks-wfmr.jdadelivers.com/retail\"\nPORTAL_URL_TESTING = \"file:///home/jared/Downloads/my_portal/PartnerPortalDocker/ExamplePortal/index.html\"\n\nPAY_RATE = 17.67\nWEEKS_IN_THE_FUTURE = 3\n\nTOKEN_PATH = pathlib.Path(\n \"/home/jared/Applications/StarbucksAutoma/credentials/token.pickle\"\n)\nCREDENTIALS_PATH = pathlib.Path(\n \"/home/jared/Applications/StarbucksAutoma/credentials/client-secret.json\"\n)\nTOKEN_JSON_PATH = pathlib.Path(\n \"/home/jared/Applications/StarbucksAutoma/credentials/token.json\"\n)\n\nCONFIG_PATH = pathlib.Path(\n \"/home/jared/Applications/StarbucksAutoma/configuration/configuration.json\"\n)\n\n\ndef default_driver() -> webdriver.Chrome:\n \"\"\"Generate a default driver\"\"\"\n\n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n options.add_argument('--no-sandbox')\n options.add_argument('--disable-dev-shm-usage')\n\n # headless_.add_argument(\"--headless\")\n\n # chromeOptions = webdriver.ChromeOptions()\n # chromeOptions.add_argument(\"--headless\") # this\n # chromeOptions.add_argument(\"--disable-gpu\")\n\n # chromeOptions.add_argument(\"--remote-debugging-port=9222\") # this\n\n driver = webdriver.Chrome(\n # executable_path=\"/home/jared/Downloads/chromedriver\",\n options=options,\n seleniumwire_options={\n \"disable_encoding\": True,\n \"request_storage\": \"memory\",\n \"request_storage_max_size\": 1,\n },\n )\n driver.scopes = [\n \"https://starbucks-wfmr.jdadelivers.com/retail/data/wfmess/api/v1-beta1/mySchedules/.*\"\n ]\n return driver\n","repo_name":"JaredDyreson/Starbucks-Automa","sub_path":"StarbucksAutoma/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"1460058756","text":"import numpy as np\nimport pytest\n\nfrom pandas import Categorical, DataFrame\n\n\n@pytest.mark.parametrize(\n \"data, expected\",\n [\n # empty\n (DataFrame(), True),\n # multi-same\n (DataFrame({\"A\": [1, 2], \"B\": [1, 2]}), True),\n # multi-object\n (\n DataFrame(\n {\n \"A\": np.array([1, 2], dtype=object),\n \"B\": np.array([\"a\", \"b\"], dtype=object),\n }\n ),\n True,\n ),\n # multi-extension\n (\n DataFrame({\"A\": Categorical([\"a\", \"b\"]), \"B\": Categorical([\"a\", \"b\"])}),\n True,\n ),\n # differ types\n (DataFrame({\"A\": [1, 2], \"B\": [1.0, 2.0]}), False),\n # differ sizes\n (\n DataFrame(\n {\n \"A\": np.array([1, 2], dtype=np.int32),\n \"B\": np.array([1, 2], dtype=np.int64),\n }\n ),\n False,\n ),\n # multi-extension differ\n (\n DataFrame({\"A\": Categorical([\"a\", \"b\"]), \"B\": Categorical([\"b\", \"c\"])}),\n False,\n ),\n ],\n)\ndef test_is_homogeneous_type(data, expected):\n assert data._is_homogeneous_type is expected\n","repo_name":"thebaselab/codeapp","sub_path":"LanguageResources/Library/lib/python3.9/site-packages/pandas/tests/frame/methods/test_is_homogeneous_dtype.py","file_name":"test_is_homogeneous_dtype.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":2422,"dataset":"github-code","pt":"80"} +{"seq_id":"23886139529","text":"from cProfile import label\nimport pickle\nimport matplotlib.pyplot as plt\nimport pdb\n\ndef paint_gragh(train_list, val_list, x_label_name, y_label_name, savefig_name):\n plt.xlabel(x_label_name)\n plt.ylabel(y_label_name)\n plt.plot(train_list, label='Train')\n plt.plot(val_list, label='Valid')\n plt.legend()\n plt.savefig(f\"{savefig_name}.jpg\")\n plt.cla()\n\ndef paint_heatmap(tensor,file_name): # heatmapを描画するメソッド\n tensor = tensor.squeeze(0) #2次元座標に変化\n plt.imshow(tensor, vmin=0, vmax=1, cmap='Blues')\n plt.savefig(f\"{file_name}\")\n\nwith open('train_data.pickle', 'rb') as r:\n train_loss_list= pickle.load(r) # img_array (N,3,H,W)\n val_loss_list = pickle.load(r) # mask array (N,1,H,W)\n train_iou_list = pickle.load(r) # edge_array (N,1,H,W)\n val_iou_list = pickle.load(r)\n\n# グラフを描画する\npaint_gragh(train_loss_list, val_loss_list, \"epoch\", \"loss\", \"loss_50\")\npaint_gragh(train_iou_list, val_iou_list, \"epoch\", \"JaccardIndex\", \"Jaccard_50\")\n","repo_name":"yossi-yuto/progressive_mirror_detection","sub_path":"paint.py","file_name":"paint.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"72977312897","text":"#!/user/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'Howie'\nimport threading,time\n\ncoun = 0\n\ndef run(n):\n global coun\n coun += 1\n time.sleep(2)\n# 用循环的方法\nt_obj = []\nlock = threading.Lock()\n\ntime_start = time.time()\nfor i in range(50):\n\n t = threading.Thread(target=run,args=('t-%s'%i,))\n t.start()\n\nprint('coun:',coun)\n\n\n","repo_name":"howardandlili/OD_pythonS14","sub_path":"Day09/threading_lock.py","file_name":"threading_lock.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"27488049623","text":"# データの読み込み\r\nimport pandas as pd\r\n\r\ndf = pd.read_csv('karaage_data.csv')\r\nprint(df.head()) # 最初の5行を表示\r\n\r\n\r\n# x:来場者[万人]\r\nx = df[['x']] \r\n# y:出店数\r\ny = df[['y']]\r\n\r\n# グラフによる可視化\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nplt.plot(x, y, 'o')\r\nplt.show()\r\n\r\n# scikit-learnも使った単回帰分析\r\nfrom sklearn.linear_model import LinearRegression\r\n\r\nmodel_lr = LinearRegression()\r\nmodel_lr.fit(x, y)\r\n\r\n# 可視化\r\nplt.plot(x, y, 'o')\r\nplt.plot(x, model_lr.predict(x), linestyle=\"solid\")\r\nplt.show()\r\n\r\nprint('モデル関数の回帰変数 w1: %.3f' %model_lr.coef_)\r\nprint('モデル関数の切片 w2: %.3f' %model_lr.intercept_)\r\nprint('y= %.3fx + %.3f' % (model_lr.coef_ , model_lr.intercept_))\r\nprint('決定係数 R^2: ', model_lr.score(x, y))\r\n","repo_name":"YuichiroSS/Machine-learning","sub_path":"single_regression.py","file_name":"single_regression.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"6525667790","text":"import numpy as np\n\n\nclass GaussianNB:\n\n def __init__(self, random_state=None, verbose=0):\n\n self.random_state = random_state\n self.verbose = int(verbose)\n self.estimator = None\n\n def fit(self, X, y, sample_weight=None):\n self.iterative_fit(X, y, n_iter=2, refit=True)\n iteration = 2\n while not self.configuration_fully_fitted():\n n_iter = int(2 ** iteration / 2)\n self.iterative_fit(X, y, n_iter=n_iter, refit=False)\n iteration += 1\n return self\n\n def iterative_fit(self, X, y, n_iter=1, refit=False):\n import sklearn.naive_bayes\n\n if refit:\n self.estimator = None\n\n if self.estimator is None:\n self.n_iter = 0\n self.fully_fit_ = False\n self.estimator = sklearn.naive_bayes.GaussianNB()\n self.classes_ = np.unique(y.astype(int))\n\n # Fallback for multilabel classification\n if len(y.shape) > 1 and y.shape[1] > 1:\n import sklearn.multiclass\n self.estimator.n_iter = self.n_iter\n self.estimator = sklearn.multiclass.OneVsRestClassifier(\n self.estimator, n_jobs=1)\n self.estimator.fit(X, y)\n self.fully_fit_ = True\n else:\n for iter in range(n_iter):\n start = min(self.n_iter * 1000, y.shape[0])\n stop = min((self.n_iter + 1) * 1000, y.shape[0])\n if X[start:stop].shape[0] == 0:\n self.fully_fit_ = True\n break\n\n self.estimator.partial_fit(X[start:stop], y[start:stop],\n self.classes_)\n self.n_iter += 1\n\n if stop >= len(y):\n self.fully_fit_ = True\n break\n\n return self\n\n def configuration_fully_fitted(self):\n if self.estimator is None:\n return False\n elif not hasattr(self, 'fully_fit_'):\n return False\n else:\n return self.fully_fit_\n\n def predict(self, X):\n if self.estimator is None:\n raise NotImplementedError\n return self.estimator.predict(X)\n\n def predict_proba(self, X):\n if self.estimator is None:\n raise NotImplementedError()\n return self.estimator.predict_proba(X)\n\n\ndef get_model(name, config, random_state):\n return (name, GaussianNB(random_state=random_state))\n","repo_name":"herilalaina/mosaic_ml","sub_path":"mosaic_ml/model_config/classification/gaussian_nb.py","file_name":"gaussian_nb.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"80"} +{"seq_id":"37088708127","text":"# 최소비용 구하기\n# https://www.acmicpc.net/problem/1916\n# https://github.com/yhs3434/Algorithms\n\nfrom heapq import heappop, heappush\n\nn = int(input())\nm = int(input())\nweight = {}\ndist = [float('inf')] * (n+1)\nfor i in range(1, n+1):\n weight[i] = {}\n\nfor _ in range(m):\n u, v, w = map(int, input().split(' '))\n if v not in weight[u]:\n weight[u][v] = w\n else:\n weight[u][v] = min(weight[u][v], w)\n\na, b = map(int, input().split(' '))\n\ndist[a] = 0\n\npq = []\nheappush(pq, (0, a))\n\nwhile pq:\n cur = heappop(pq)\n cost = cur[0]\n here = cur[1]\n\n if dist[here] >= cost:\n for there in weight[here]:\n nextDist = cost + weight[here][there]\n if nextDist < dist[there]:\n dist[there] = nextDist\n heappush(pq, (nextDist, there))\nprint(dist[b])","repo_name":"yhs3434/Algorithms","sub_path":"baekjun/classification/dijkstra/1916.py","file_name":"1916.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"80"} +{"seq_id":"39833885228","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport cv2 \nfrom PIL import Image \nimport matplotlib.pyplot as plt \nimport numpy as np \n\n\n# In[4]:\n\n\nfrom utils import visualize \nimport pickle \nwith open(\"./data.pkl\", 'rb') as f: \n dataset = pickle.load(f)\n\n\n# In[5]:\n\n\ndata_ab = dataset[\"4cells\"] # list of list of numpy matrices \n\n\n# In[6]:\n\n\ndata_cde = dataset[\"9cells\"] \n\n\n# In[7]:\n\n\nvisualize(data_ab[0])\n\n\n# In[8]:\n\n\n# Brute-Force Matching with ORB Descriptors \nimg1 = data_ab[0][0]\nimg2 = data_ab[0][9]\n# Initiate ORB detector\norb = cv2.ORB_create()\n# find the keypoints and descriptors with ORB\nkp1, des1 = orb.detectAndCompute(img1,None)\nkp2, des2 = orb.detectAndCompute(img2,None)\n\n\n# create BFMatcher object\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n# Match descriptors.\nmatches = bf.match(des1,des2)\n# Sort them in the order of their distance.\nmatches = sorted(matches, key = lambda x:x.distance)\nprint(sum([matches[i].distance for i in range(10)]))\n# Draw first 10 matches.\nimg3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:],None,flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\nplt.imshow(img3),plt.show()\n\n\n# In[23]:\n\n\nprint(type(kp1))\nprint(type(des1))\n\n\n# In[25]:\n\n\nprint(len(kp1)) \nprint(type(kp1[0]))\n\n\n# In[26]:\n\n\nprint(kp1)\n\n\n# In[27]:\n\n\nprint(des1.shape)\n\n\n# In[28]:\n\n\nplt.imshow(des1), plt.show()\n\n\n# In[29]:\n\n\nprint(img1.shape)\n\n\n# In[30]:\n\n\nprint(type(matches))\nprint(len(matches))\n\n\n# In[31]:\n\n\nprint(type(matches[0]))\n\n\n# In[32]:\n\n\nprint(matches[0])\n\n\n# In[45]:\n\n\nprint(matches[10].distance)\n\n\n# In[9]:\n\n\nimg1 = data_ab[0][0]\nimg2 = data_ab[0][9] \n# Initiate SIFT detector \nsift = cv2.xfeatures2d.SIFT_create()\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1,None)\nkp2, des2 = sift.detectAndCompute(img2,None)\n# BFMatcher with default params\nbf = cv2.BFMatcher()\nmatches = bf.knnMatch(des1,des2,k=2)\n# Apply ratio test\ngood = []\nfor m,n in matches:\n if m.distance < 0.75*n.distance:\n good.append([m])\n# cv.drawMatchesKnn expects list of lists as matches.\nimg3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)\nplt.imshow(img3),plt.show()\n\n\n# In[10]:\n\n\nsift = cv2.xfeatures2d.SIFT_create()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"deepweaver/ravens","sub_path":"Solver/FeatureMatcherPlayground.py","file_name":"FeatureMatcherPlayground.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"70016767299","text":"'''\n124 Following Orders\nTopological Sort\n\nWe track a set of \"good\" variables that are free to be picked in that moment\nWe recoursively make a copy of this set and pick each of them, one at a time and then update the good variables\nWhen we have picked all the variables we print them out and backtrack\n'''\nfrom sys import stdin, stdout\nalpha = set('asqxwczdevrftbghynumijklop')\nfirst = True\nwhile True:\n line = stdin.readline()\n if line == '':\n break\n if first:\n first = False\n else:\n stdout.write('\\n')\n \n v = sorted([q for q in list(line) if q in alpha])\n translation = {v[i]: i for i in range(len(v))}\n line = stdin.readline() \n c = [q for q in list(line) if q in alpha]\n # a before b\n abb = [set() for i in range(len(v))]\n # a after b\n aab = [set() for i in range(len(v))]\n for i in range(0, len(c), 2):\n abb[translation[c[i]]].add(translation[c[i+1]])\n aab[translation[c[i+1]]].add(translation[c[i]])\n good = set()\n picked = []\n for i in range(len(v)):\n if len(aab[i]) == 0:\n good.add(i)\n # print (good)\n def try_all():\n if len(picked) == len(v):\n stdout.write(''.join([v[p] for p in picked]))\n stdout.write('\\n')\n else:\n okay = set(good)\n for g in okay:\n if g in good:\n good.remove(g)\n picked.append(g)\n coup = []\n toogood = set()\n for after in abb[g]:\n if g in aab[after]:\n coup.append((after, g))\n aab[after].remove(g)\n if len(aab[after]) == 0:\n good.add(after)\n toogood.add(after)\n try_all()\n for c in coup:\n aab[c[0]].add(c[1])\n for tg in toogood:\n if tg in good:\n good.remove(tg)\n picked.pop()\n good.add(g)\n try_all()\n","repo_name":"chq-matteo/uva-oj","sub_path":"src/swerc2017/124.py","file_name":"124.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"71164403457","text":"from abc import abstractmethod\nimport os\nfrom pathlib import Path\nimport re\nimport time\n\nfrom django.conf import settings\nfrom django.shortcuts import reverse\nfrom djaveAPI.status_codes import is_server_error\nfrom djaveClassMagic.find_models import all_models\nfrom djaveLogin.calc_urls import append_next_url, NEXT_URL\nfrom djaveReport.date_range_report import FROM_DATE, TO_DATE\nfrom djaveURL import dict_as_query\nimport requests\n\n\n# all_web_tests means that I don't have to maintain a list of existing web\n# tests. I can just scan for them. In order for all_web_tests to work, every\n# app's web tests need to be imported into my_specific_app/web_test/__init__.py\n# The downside to that is, when unit tests run, the unit test loader ends up\n# scanning through all the files and running all the imports. Normally this\n# would be fine, but selenium is a special case. It's only needed locally for\n# web testing. The last time I tried to deploy it as a dependency to Heroku,\n# Heroku freaked out with incomprehensible error messages. Hence we need to do\n# this hack where selenium stuff is imported within functions so as to avoid\n# import errors when unit tests run as part of continuous integration.\n\n\ndef all_web_tests():\n return all_models(WebTest)\n\n\nclass WebTest(object):\n def __init__(self, server):\n self.server = server\n self.driver = None\n\n @abstractmethod\n def run(self):\n raise NotImplementedError('run')\n\n def pre_run(self):\n from selenium import webdriver\n # Chrome seems to raise a bunch more selenium exceptions, like element not\n # interactable or stale element reference. I WISH I could use just regular\n # old Chrome purely because it has a beautiful speaking voice for the demo.\n # Buuuut you aren't allowed to use Chrome exactly, you have to use Chromium\n # or something, which ships with no voices. The sparse help I could find\n # online about this was about hooking Chromium up to espeak, but espeak\n # sounds just as bad as Firefox. So as far as I can tell, there's no way\n # to use Chrome's beautiful speaking voice in my demos :( That's not all\n # though. self.driver =\n # webdriver.Chrome(service_args=['--enable-speech-dispatcher'])\n self.driver = webdriver.Firefox()\n\n def close_driver(self):\n from selenium.common.exceptions import SessionNotCreatedException\n if self.driver:\n try:\n self.driver.close()\n except SessionNotCreatedException:\n # The driver is closed already.\n pass\n\n def go_to_url(self, url):\n self.maybe_pause()\n self.driver.get(url)\n self.close_django_toolbar()\n if self.on_django_server_error_screen():\n raise Exception(\n 'It appears I am on an error screen and the test has failed.')\n\n def on_django_server_error_screen(self):\n return bool(\n self.finds('exception_value', raise_exception_if_not_found=False))\n\n def go_to_view(self, view_name, query_string='', **kwargs):\n url = self.server_plus_reverse(view_name, **kwargs)\n if query_string:\n if query_string[0] != '?':\n url += '?'\n url += query_string\n self.go_to_url(url)\n\n def go_to_dated_report(self, view_name, from_date, to_date):\n query_string = dict_as_query({\n FROM_DATE: from_date.isoformat(), TO_DATE: to_date.isoformat()})\n self.go_to_view(view_name, query_string=query_string)\n\n def get_view_json(self, view_name, *args, **kwargs):\n response = requests.get(\n self.server_plus_reverse(view_name, *args, **kwargs))\n if is_server_error(response):\n if self.server == 'http://127.0.0.1:8000':\n raise Exception('Server error. Look at your ./manage.py runserver')\n raise Exception('Server error. Check {}/admin/errors/stayderror/'.format(\n self.server))\n return response.json()\n\n def server_plus_reverse(self, view_name, *args, **kwargs):\n path = reverse(view_name, args=args, kwargs=kwargs)\n return '{}{}'.format(self.server, path)\n\n def close_django_toolbar(self):\n from selenium.common.exceptions import NoSuchElementException\n # The debug toolbar gets in the way of elements when you try to click on\n # them sometimes.\n try:\n toolbar = self.driver.find_element_by_id('djDebugToolbar')\n if toolbar.value_of_css_property('display') == 'block':\n self.driver.find_element_by_id('djHideToolBarButton').click()\n except NoSuchElementException:\n pass\n\n def default_server(self):\n # return settings.STAGE_SERVER is also a common one. Or you can just do\n # ./manage.py my_web_test --server=https://stage.hihoward.com\n return 'http://127.0.0.1:8000'\n\n def wait(self, seconds):\n \"\"\" Seconds can be a float \"\"\"\n time.sleep(seconds)\n\n def wait_closure(\n self, closure, error_message=None, wait_seconds=10,\n fail_on_timeout=True):\n attempts = 0\n poll_interval = 0.1\n max_attempts = wait_seconds / poll_interval\n while attempts < max_attempts:\n if closure():\n return\n self.wait(poll_interval)\n attempts += 1\n if fail_on_timeout:\n raise Exception(error_message or 'Closure was never True')\n\n def maybe_pause(self):\n \"\"\" When you're using ./manage.py runserver --settings\n main.web_test_settings you can press ` to pause and unpause during\n web demos and tests. \"\"\"\n def done():\n return self._js_variable_undefined_or_true('un_pause')\n self.wait_closure(done, wait_seconds=8 * 60 * 60)\n\n def wait_for_class(self, class_name):\n from selenium.webdriver.common.by import By\n from selenium.webdriver.support.ui import WebDriverWait\n from selenium.webdriver.support import expected_conditions\n WebDriverWait(self.driver, 10).until(\n expected_conditions.presence_of_element_located(\n (By.CLASS_NAME, class_name)))\n return self.find(class_name)\n\n def wait_for_xpath(self, xpath):\n from selenium.webdriver.common.by import By\n from selenium.webdriver.support.ui import WebDriverWait\n from selenium.webdriver.support import expected_conditions\n WebDriverWait(self.driver, 10).until(\n expected_conditions.presence_of_element_located(\n (By.XPATH, xpath)))\n return self.driver.find_element_by_xpath(xpath)\n\n def wait_for_text(self, xpath, expected_text):\n from selenium.webdriver.common.by import By\n from selenium.webdriver.support.ui import WebDriverWait\n from selenium.webdriver.support import expected_conditions\n WebDriverWait(self.driver, 10).until(\n expected_conditions.text_to_be_present_in_element(\n (By.XPATH, xpath), expected_text))\n return self.driver.find_element_by_xpath(xpath)\n\n def raise_if_on_error_screen(self):\n if self.on_error_screen():\n message = 'There\\'s an on-screen Django error. '\n if settings.LOCAL:\n message += 'Check your ./manage.py runserver. '\n else:\n message += 'Check for server error emails from {}. '.format(\n settings.THIS_SERVERS_BASE_URL)\n message += 'The error message is: {}'.format(\n self.driver.find_element_by_xpath('//div[@id=\"summary\"]/pre').text)\n raise Exception(message)\n\n def on_error_screen(self):\n return 1 == len(self.driver.find_elements_by_id('traceback'))\n\n def click_button(self, container_or_button_id):\n from selenium.common.exceptions import NoSuchElementException\n try:\n button = self.driver.find_element_by_xpath(\n '//*[@id=\"{}\"]//*[@class=\"button\"]'.format(container_or_button_id))\n except NoSuchElementException:\n button = self.driver.find_element_by_xpath(\n '//*[@id=\"{}\"]'.format(container_or_button_id))\n assert button.is_displayed()\n button.click()\n\n def screen_height(self):\n return self.driver.execute_script('return window.screen.height;')\n\n def scrolled_to(self):\n return self.driver.execute_script('return window.pageYOffset;')\n\n def is_scrolled_to(self, element):\n scrolled_to = self.scrolled_to()\n screen_height = self.screen_height()\n above = scrolled_to < element.location['y']\n below = scrolled_to + screen_height >= element.location['y']\n return above and below\n\n def scroll_to_bottom(self):\n self._scroll('document.body.scrollHeight')\n\n def scroll_to_element(self, element_or_clue):\n element = self.get_element(element_or_clue)\n self._scroll(str(element.location['y']))\n\n def _scroll(self, scrollTop):\n script = (\n \"$('html, body').animate(\"\n \"{scrollTop: \" + scrollTop + \"}, 800);\")\n self.driver.execute_script(script)\n self.wait(.8)\n\n def img_path(self, img_file_name):\n this_dir = os.path.dirname(os.path.realpath(__file__))\n app_dir = Path(this_dir).parent.as_posix()\n img_dir = os.path.join(app_dir, 'static')\n return os.path.join(img_dir, img_file_name)\n\n def do_file_upload(self, container, img_path):\n id_upload = container.find_element_by_xpath('.//input[@type=\"file\"]')\n id_upload.send_keys(img_path)\n\n def login(self, email_address):\n self.find('email').send_keys(email_address)\n self.find('emailmealoginlink').click()\n self.click_login_link(email_address)\n\n def enter_date(self, element, date):\n element.send_keys(date.isoformat())\n\n def click_sign_up_link(self, email_address):\n self._click_login_or_sign_up_helper(email_address, 'djave_sign_up')\n\n def click_login_link(self, email_address):\n self._click_login_or_sign_up_helper(email_address, 'djave_login')\n\n def _click_login_or_sign_up_helper(self, email_address, view_name):\n find_login_token_url = '{}?email={}'.format(\n self.server_plus_reverse('login_token'), email_address)\n token = requests.get(find_login_token_url).json()['token']\n next_url = None\n next_url_finder = re.compile('{}=(.+)'.format(NEXT_URL))\n found = next_url_finder.findall(self.driver.current_url)\n if found:\n next_url = found[0]\n login_url = append_next_url(\n self.server_plus_reverse(view_name, token=token), next_url)\n self.go_to_url(login_url)\n\n def find(self, clue):\n return self.finds(clue)[0]\n\n def finds(self, clue, raise_exception_if_not_found=True, attempt=0):\n elts = self.driver.find_elements_by_class_name(clue)\n if len(elts):\n return elts\n elts = self.driver.find_elements_by_name(clue)\n if len(elts):\n return elts\n elts = self.driver.find_elements_by_id(clue)\n if len(elts):\n return elts\n elts = self.driver.find_elements_by_tag_name(clue)\n if len(elts):\n return elts\n if raise_exception_if_not_found:\n if attempt == 3:\n raise Exception('I was unable to find {}'.format(clue))\n time.sleep(.5)\n return self.finds(\n clue, raise_exception_if_not_found=raise_exception_if_not_found,\n attempt=attempt + 1)\n\n def find_with_value(self, clue, value):\n for elt in self.finds(clue):\n if elt.get_property('value') == value:\n return elt\n raise Exception('Never found {} with value {}'.format(clue, value))\n\n def find_pk(self, elt):\n return int(\n elt.find_element_by_xpath('ancestor::tr').get_attribute('data-pk'))\n\n def find_with_text(self, tag_name, text):\n found = self.finds_with_text(tag_name, text)\n if found:\n return found[0]\n raise Exception('I was unable to find a {} with {}'.format(tag_name, text))\n\n def finds_with_text(self, tag_name, text):\n found = []\n for elt in self.driver.find_elements_by_tag_name(tag_name):\n if elt.text.find(text) >= 0:\n found.append(elt)\n return found\n\n def get_element(self, element_or_clue):\n if isinstance(element_or_clue, str):\n return self.find(element_or_clue)\n return element_or_clue\n","repo_name":"dasmith2/djaveTest","sub_path":"djaveTest/web_test.py","file_name":"web_test.py","file_ext":"py","file_size_in_byte":11605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"75075187778","text":"from aocd.models import Puzzle\nfrom typing import Tuple, Dict\nfrom collections import defaultdict\nfrom itertools import combinations, product, count\nfrom functools import lru_cache, reduce\nfrom operator import mul\nimport re\n\npuzzle = Puzzle(year=2020, day=25)\n\npublic_keys = [int(x) for x in puzzle.input_data.splitlines()]\n\ndef transform(subject_number:int, loop_size:int) -> int:\n value = 1\n for i in range(loop_size):\n value *= subject_number\n value %= 20201227 # magic number\n return value\n\ndef find_loop(target:int) -> int:\n value = 1\n subject_number = 7\n for i in count(1):\n value *= subject_number\n value %= 20201227 # magic number\n if value == target:\n break\n return i\n\nanswer_a = transform(public_keys[1], find_loop(public_keys[0]))\nprint(answer_a)\npuzzle.answer_a = answer_a","repo_name":"fillund/Advent-of-code","sub_path":"2020/Day25.py","file_name":"Day25.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38046735488","text":"from django.core.management import BaseCommand\n\nfrom manage_store.models import ProjectSettings\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n \"\"\"\n Команда для установки настроек (создание инстансов модели ProjectSettings\n \"\"\"\n self.stdout.write('Запуск команды по установке настроек')\n default_settings = (\n ('time_to_delete', 60*36), # Время до удаления файлов, после скачивания клиентом\n ('admin_time_to_del', 120), # Время до удаления файлов, после действия админа\n )\n for i_key, i_val in default_settings:\n setting_obj, created = ProjectSettings.objects.update_or_create(\n key=i_key,\n defaults={\n 'key': i_key,\n 'value': i_val,\n }\n )\n if created:\n self.stdout.write(f'Создана настройка ключ={setting_obj.key}, значение={setting_obj.value}')\n else:\n self.stdout.write(f'Обновлена настройка ключ={setting_obj.key}, значение={setting_obj.value}')\n self.stdout.write(self.style.SUCCESS('Установка настроек закончена!'))\n","repo_name":"DaniilSh23/groha_shop_manage","sub_path":"manage_store/management/commands/set_settings.py","file_name":"set_settings.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40099700266","text":"import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom mmseg.models.builder import LOSSES\nfrom mmseg.models.losses.cross_entropy_loss import CrossEntropyLoss\nfrom .tree_triplet_loss import TreeTripletLoss\n\nhiera_map = [0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 6, 6, 6, 6, 6, 6]\nhiera_index = [[0, 2], [2, 5], [5, 8], [8, 10], [10, 11], [11, 13], [13, 19]]\n\nhiera = {\n 'hiera_high': {\n 'flat': [0, 2],\n 'construction': [2, 5],\n 'object': [5, 8],\n 'nature': [8, 10],\n 'sky': [10, 11],\n 'human': [11, 13],\n 'vehicle': [13, 19]\n }\n}\n\n\ndef prepare_targets(targets):\n b, h, w = targets.shape\n targets_high = torch.ones(\n (b, h, w), dtype=targets.dtype, device=targets.device) * 255\n indices_high = []\n for index, high in enumerate(hiera['hiera_high'].keys()):\n indices = hiera['hiera_high'][high]\n for ii in range(indices[0], indices[1]):\n targets_high[targets == ii] = index\n indices_high.append(indices)\n\n return targets, targets_high, indices_high\n\n\ndef losses_hiera(predictions,\n targets,\n targets_top,\n num_classes,\n indices_high,\n eps=1e-8):\n \"\"\"Implementation of hiera loss.\n\n Args:\n predictions (torch.Tensor): seg logits produced by decode head.\n targets (torch.Tensor): The learning label of the prediction.\n targets_top (torch.Tensor): The hierarchy ground truth of the learning\n label.\n num_classes (int): Number of categories.\n indices_high (List[List[int]]): Hierarchy indices of each hierarchy.\n eps (float):Term added to the Logarithm to improve numerical stability.\n \"\"\"\n b, _, h, w = predictions.shape\n predictions = torch.sigmoid(predictions.float())\n void_indices = (targets == 255)\n targets[void_indices] = 0\n targets = F.one_hot(targets, num_classes=num_classes).permute(0, 3, 1, 2)\n void_indices2 = (targets_top == 255)\n targets_top[void_indices2] = 0\n targets_top = F.one_hot(targets_top, num_classes=7).permute(0, 3, 1, 2)\n\n MCMA = predictions[:, :num_classes, :, :]\n MCMB = torch.zeros((b, 7, h, w)).to(predictions)\n for ii in range(7):\n MCMB[:, ii:ii + 1, :, :] = torch.max(\n torch.cat([\n predictions[:, indices_high[ii][0]:indices_high[ii][1], :, :],\n predictions[:, num_classes + ii:num_classes + ii + 1, :, :]\n ],\n dim=1), 1, True)[0]\n\n MCLB = predictions[:, num_classes:num_classes + 7, :, :]\n MCLA = predictions[:, :num_classes, :, :].clone()\n for ii in range(7):\n for jj in range(indices_high[ii][0], indices_high[ii][1]):\n MCLA[:, jj:jj + 1, :, :] = torch.min(\n torch.cat([\n predictions[:, jj:jj + 1, :, :], MCLB[:, ii:ii + 1, :, :]\n ],\n dim=1), 1, True)[0]\n\n valid_indices = (~void_indices).unsqueeze(1)\n num_valid = valid_indices.sum()\n valid_indices2 = (~void_indices2).unsqueeze(1)\n num_valid2 = valid_indices2.sum()\n # channel_num*sum()/one_channel_valid already has a weight\n loss = (\n (-targets[:, :num_classes, :, :] * torch.log(MCLA + eps) -\n (1.0 - targets[:, :num_classes, :, :]) * torch.log(1.0 - MCMA + eps))\n * valid_indices).sum() / num_valid / num_classes\n loss += ((-targets_top[:, :, :, :] * torch.log(MCLB + eps) -\n (1.0 - targets_top[:, :, :, :]) * torch.log(1.0 - MCMB + eps)) *\n valid_indices2).sum() / num_valid2 / 7\n\n return 5 * loss\n\n\ndef losses_hiera_focal(predictions,\n targets,\n targets_top,\n num_classes,\n indices_high,\n eps=1e-8,\n gamma=2):\n \"\"\"Implementation of hiera loss.\n\n Args:\n predictions (torch.Tensor): seg logits produced by decode head.\n targets (torch.Tensor): The learning label of the prediction.\n targets_top (torch.Tensor): The hierarchy ground truth of the learning\n label.\n num_classes (int): Number of categories.\n indices_high (List[List[int]]): Hierarchy indices of each hierarchy.\n eps (float):Term added to the Logarithm to improve numerical stability.\n Defaults: 1e-8.\n gamma (int): The exponent value. Defaults: 2.\n \"\"\"\n b, _, h, w = predictions.shape\n predictions = torch.sigmoid(predictions.float())\n void_indices = (targets == 255)\n targets[void_indices] = 0\n targets = F.one_hot(targets, num_classes=num_classes).permute(0, 3, 1, 2)\n void_indices2 = (targets_top == 255)\n targets_top[void_indices2] = 0\n targets_top = F.one_hot(targets_top, num_classes=7).permute(0, 3, 1, 2)\n\n MCMA = predictions[:, :num_classes, :, :]\n MCMB = torch.zeros((b, 7, h, w),\n dtype=predictions.dtype,\n device=predictions.device)\n for ii in range(7):\n MCMB[:, ii:ii + 1, :, :] = torch.max(\n torch.cat([\n predictions[:, indices_high[ii][0]:indices_high[ii][1], :, :],\n predictions[:, num_classes + ii:num_classes + ii + 1, :, :]\n ],\n dim=1), 1, True)[0]\n\n MCLB = predictions[:, num_classes:num_classes + 7, :, :]\n MCLA = predictions[:, :num_classes, :, :].clone()\n for ii in range(7):\n for jj in range(indices_high[ii][0], indices_high[ii][1]):\n MCLA[:, jj:jj + 1, :, :] = torch.min(\n torch.cat([\n predictions[:, jj:jj + 1, :, :], MCLB[:, ii:ii + 1, :, :]\n ],\n dim=1), 1, True)[0]\n\n valid_indices = (~void_indices).unsqueeze(1)\n num_valid = valid_indices.sum()\n valid_indices2 = (~void_indices2).unsqueeze(1)\n num_valid2 = valid_indices2.sum()\n # channel_num*sum()/one_channel_valid already has a weight\n loss = ((-targets[:, :num_classes, :, :] * torch.pow(\n (1.0 - MCLA), gamma) * torch.log(MCLA + eps) -\n (1.0 - targets[:, :num_classes, :, :]) * torch.pow(MCMA, gamma) *\n torch.log(1.0 - MCMA + eps)) *\n valid_indices).sum() / num_valid / num_classes\n loss += (\n (-targets_top[:, :, :, :] * torch.pow(\n (1.0 - MCLB), gamma) * torch.log(MCLB + eps) -\n (1.0 - targets_top[:, :, :, :]) * torch.pow(MCMB, gamma) *\n torch.log(1.0 - MCMB + eps)) * valid_indices2).sum() / num_valid2 / 7\n\n return 5 * loss\n\n\n@LOSSES.register_module()\nclass HieraTripletLossCityscape(nn.Module):\n \"\"\"Modified from https://github.com/qhanghu/HSSN_pytorch/blob/main/mmseg/mo\n dels/losses/hiera_triplet_loss_cityscape.py.\"\"\"\n\n def __init__(self, num_classes, use_sigmoid=False, loss_weight=1.0):\n super().__init__()\n self.num_classes = num_classes\n self.loss_weight = loss_weight\n self.treetripletloss = TreeTripletLoss(num_classes, hiera_map,\n hiera_index)\n self.ce = CrossEntropyLoss()\n\n def forward(self,\n step,\n embedding,\n cls_score_before,\n cls_score,\n label,\n weight=None,\n **kwargs):\n targets, targets_top, indices_top = prepare_targets(label)\n\n loss = losses_hiera(cls_score, targets, targets_top, self.num_classes,\n indices_top)\n ce_loss = self.ce(cls_score[:, :-7], label)\n ce_loss2 = self.ce(cls_score[:, -7:], targets_top)\n loss = loss + ce_loss + ce_loss2\n\n loss_triplet, class_count = self.treetripletloss(embedding, label)\n class_counts = [\n torch.ones_like(class_count)\n for _ in range(torch.distributed.get_world_size())\n ]\n torch.distributed.all_gather(class_counts, class_count, async_op=False)\n class_counts = torch.cat(class_counts, dim=0)\n\n if torch.distributed.get_world_size() == torch.nonzero(\n class_counts, as_tuple=False).size(0):\n factor = 1 / 4 * (1 + torch.cos(\n torch.tensor((step.item() - 80000) / 80000 *\n math.pi))) if step.item() < 80000 else 0.5\n loss += factor * loss_triplet\n\n return loss * self.loss_weight\n","repo_name":"open-mmlab/mmsegmentation","sub_path":"projects/hssn/losses/hiera_triplet_loss_cityscape.py","file_name":"hiera_triplet_loss_cityscape.py","file_ext":"py","file_size_in_byte":8433,"program_lang":"python","lang":"en","doc_type":"code","stars":6731,"dataset":"github-code","pt":"80"} +{"seq_id":"13320537753","text":"from base64 import b64encode\r\nfrom Crypto.Cipher import AES\r\nfrom Crypto.Util.Padding import pad\r\nfrom Crypto.Util.Padding import unpad\r\n\r\nINPUT_FILE = \"test_files/quizzed.wav\"\r\n\r\nkey = b\"SymphonyOfBabel_\"\r\ncipher = AES.new(key, AES.MODE_CBC, iv=b\"SymphonyOfBabel_\")\r\n\r\nwith open(INPUT_FILE, \"rb\") as f:\r\n header = f.read(44)\r\n data = f.read()\r\n\r\nct_bytes = cipher.encrypt(pad(data, AES.block_size))\r\niv = b64encode(cipher.iv).decode('utf-8')\r\n\r\nperformerName = ct_bytes[:100].decode(\"cp437\")\r\nsongTitle = ct_bytes[100:200].decode(\"cp437\")\r\ndate = int.from_bytes(ct_bytes[200:208], \"big\")\r\ntrackNumber = int.from_bytes(ct_bytes[208:210], \"big\")\r\nimage = ct_bytes[210:960000]\r\n\r\nprint(f\"PerformerName ({len(performerName)}): {performerName}\")\r\nprint(f\"SongTitle ({len(songTitle)}): {songTitle}\")\r\nprint(f\"Date: {date}\")\r\nprint(f\"Track: {trackNumber}\")\r\n\r\ncipher = AES.new(key, AES.MODE_CBC, iv=b\"SymphonyOfBabel_\")\r\npt = unpad(cipher.decrypt(ct_bytes), AES.block_size)\r\n\r\nwith open('test_files/quizzed_decrypted.wav', \"wb\") as f:\r\n f.write(header)\r\n f.write(pt)\r\n\r\n","repo_name":"NickXitco/symphonyofbabel","sub_path":"wav-parser/wavFileInput.py","file_name":"wavFileInput.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"29682142642","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom admin.models import *\nfrom django.utils import timezone\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.contrib import messages\n\n# Create your views here.\n\n# 사용자 메인페이지\ndef main(request):\n return render(request, 'mainpage/introduce.html')\n\n# 메뉴\ndef menu(request):\n\n # 로그인을 하지 않았을 시 로그인이 필요하다는 메세지를 보여줍니다.\n if request.user.id == None:\n return HttpResponse(\n '')\n\n if request.method == \"POST\":\n # QueryDict 를 딕셔너리로 변환.(상품 일련번호를 리스트로 가져오기 위함)\n mydict = dict(request.POST)\n\n # 상품을 선택하지 않고 주문하기를 눌렀을 경우 예외처리\n try:\n # 상품 일련번호 리스트\n gd_no_list = mydict['gd_no']\n except:\n return HttpResponse(\n '')\n\n try:\n # 마지막 주문 객체\n last_order = order_tbl.objects.last()\n # 마지막 주문 객체의 주문번호\n pre_od_number = last_order.od_number\n # 이전 주문 번호에 1을 더한 값을 주문번호로 합니다.\n od_number = pre_od_number + 1\n except:\n # 이전 주문이 없을 경우 1부터 시작\n od_number = 1\n\n # 주소 등록이 되어있지 않은 경우 오류 메세지를 보여준 후 메인 페이지로 돌아갑니다.\n try:\n new_address = request.user.c_new_address.split(' ')\n except:\n return HttpResponse(\n '')\n\n # 시,도\n city = new_address[0]\n\n # ~시(ex 성남시)\n borough = new_address[1]\n\n\n # 배송 담당자 객체를 불러 옵니다\n try:\n shipper = shipper_tbl.objects.get(sp_city=city, sp_borough=borough)\n except:\n # 배송 담당자가 없을 경우 배송할 수 없는 지역이라는 문구를 띄웁니다.\n return HttpResponse(\n '')\n\n\n\n # for문을 통해 주문 객체 생성\n for gd_no in gd_no_list:\n # 주문 객체를 생성\n order_tbl.objects.create(od_number=od_number, od_state=False, customer_id=request.user.id, gd_no_id=gd_no, od_zip_code=request.user.c_zip_code,\n od_address=request.user.c_new_address, od_address_detail=request.user.c_address_detail,sp_no_id=shipper.sp_no)\n\n # 상품 객체를 가져 옵니다.\n goods = goods_tbl.objects.get(gd_no=gd_no)\n # 상품을 주문 했으므로 상품의 재고를 1개 차감.\n goods.gd_stock = goods.gd_stock - 1\n # DB에 저장(수정)\n goods.save()\n\n return HttpResponse(\n '')\n\n\n # 밥류 리스트\n rice_list = goods_tbl.objects.filter(gd_category='밥류')\n # 샌드위치류 리스트\n sandwich_list = goods_tbl.objects.filter(gd_category='샌드위치류')\n # 샐러드류 리스트\n salad_list = goods_tbl.objects.filter(gd_category='샐러드류')\n # 누들류 리스트\n noodle_list = goods_tbl.objects.filter(gd_category='누들류')\n # 기타\n etc_list = goods_tbl.objects.filter(gd_category='기타')\n\n context = {'rice_list' : rice_list, 'sandwich_list' : sandwich_list, 'salad_list' : salad_list, 'noodle_list' : noodle_list, 'etc_list' : etc_list}\n return render(request, 'mainpage/menu.html', context)\n\n# 주문 목록\ndef order_list(request):\n\n # 로그인을 하지 않았을 시 로그인이 필요하다는 메세지를 보여줍니다.\n if request.user.id == None:\n return HttpResponse(\n '')\n\n # 접속한 고객의 주문 목록 리스트를 불러옵니다.\n order_list = order_tbl.objects.filter(customer_id=request.user.id)\n context = {'order_list' : order_list}\n\n return render(request, 'mainpage/order_list.html', context)\n\n# 로그아웃\ndef user_logout(request):\n logout(request)\n\n return redirect('/')\n","repo_name":"joy3968/wehuddling","sub_path":"weeat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4884,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"35363675686","text":"import re\nfrom collections import defaultdict\n\n\nwith open(\"15_input.txt\") as f:\n raw_data = f.read().strip().splitlines()\n\nline_regexp = re.compile(r\"x=(-?\\d+).+y=(-?\\d+).+x=(-?\\d+).+y=(-?\\d+)\")\nsensor_beacons = []\nfor line in raw_data:\n sx, sy, bx, by = list(map(int, line_regexp.findall(line)[0]))\n sensor_beacons.append((sx, sy, bx, by))\n\n\ndef part_1(sensor_beacons):\n track_y = 2000000\n tracked_positions = set()\n\n for sx, sy, bx, by in sensor_beacons:\n size = abs(sx - bx) + abs(sy - by)\n\n distance = abs(abs(sy) - abs(track_y))\n if distance > size:\n continue\n\n points_length = 1 + 2 * (size - distance)\n start_x = sx - (size - distance)\n start_y = track_y\n\n for i in range(points_length):\n tracked_positions.add((start_x + i, start_y))\n\n for sx, sy, bx, by in sensor_beacons:\n if (sx, sy) in tracked_positions:\n tracked_positions.remove((sx, sy))\n if (bx, by) in tracked_positions:\n tracked_positions.remove((bx, by))\n\n return len(tracked_positions)\n\n\ndef _find_beacon(tracked_positions: dict[int, list[tuple[int, int]]]):\n for y, xs in tracked_positions.items():\n xs.sort(key=lambda y: y[0])\n rx1, rx2 = xs[0]\n for x1, x2 in xs[1:]:\n if rx2 < x1:\n return rx2 + 1, y\n\n if rx2 < x2:\n rx2 = x2\n\n raise ValueError(\"No beacon found\")\n\n\ndef part_2(sensor_beacons):\n tracked_positions = defaultdict(list)\n for sx, sy, bx, by in sensor_beacons:\n size = abs(sx - bx) + abs(sy - by)\n\n for track_y in range(0, 4000000):\n distance = abs(abs(sy) - abs(track_y))\n if distance > size:\n continue\n\n points_length = 1 + 2 * (size - distance)\n start_x = sx - (size - distance)\n start_y = track_y\n\n tracked_positions[start_y].append((start_x, start_x + points_length - 1))\n\n beacon = _find_beacon(tracked_positions)\n return beacon[0] * 4000000 + beacon[1]\n\n\nprint(\"Part 1:\", part_1(sensor_beacons))\nprint(\"Part 2:\", part_2(sensor_beacons))\n","repo_name":"Ziken/aoc2022","sub_path":"15_day.py","file_name":"15_day.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"22342141492","text":"from typing import List\r\n\r\n\r\nclass Solution:\r\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\r\n start = 0\r\n endValue = len(letters) - 1\r\n if ((target == letters[start]) and (target < letters[start + 1])):\r\n return letters[start + 1]\r\n\r\n elif (target == letters[endValue]):\r\n return letters[0]\r\n\r\n else:\r\n while (start != endValue):\r\n mid = int(start + (endValue - start) / 2)\r\n if (target == letters[mid]) and (letters[mid] < letters[mid + 1]):\r\n print(\"hi\")\r\n return letters[mid + 1]\r\n\r\n elif (target > letters[mid - 1] and target < letters[mid]):\r\n print(\"hi1\")\r\n return letters[mid]\r\n\r\n elif (target < letters[mid + 1] and target > letters[mid]):\r\n print(\"h12\")\r\n return letters[mid + 1]\r\n\r\n elif (target < letters[mid]):\r\n endValue = mid - 1\r\n\r\n else:\r\n start = mid + 1\r\n\r\n return letters[0]\r\n\r\n\r\nletters = [\"e\", \"e\", \"e\", \"k\", \"q\", \"q\", \"q\", \"v\", \"v\", \"y\"]\r\n\r\ntarget = \"k\"\r\n\r\nprint(Solution().nextGreatestLetter(letters=letters, target=target))\r\n\r\n\r\n","repo_name":"shivamkr9/Data_Structure_and_Algorithm_in_Puthon","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"70360244419","text":"import sys\nn = int(input())\nmaze = [0]*(n+1)\npsum = [0]*(n+1)\n\nfor _ in range(n):\n v, m = map(int, input().split())\n maze[v] = m\n psum[v] = m + psum[v-1]\n\nfor i in range(1, n+1):\n if psum[i] >= psum[n] - psum[i]:\n print(i)\n quit()\n","repo_name":"chtw2001/algorithm","sub_path":"etc/2141(un).py","file_name":"2141(un).py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"26021749450","text":"import numpy as np\n\n\ndef avaliate_macd(df, window_small, window_large):\n avg_small = df.Close.ewm(span=window_small, min_periods=window_small).mean()\n\n # Calculate and define moving average of window_large periods\n avg_large = df.Close.ewm(span=window_large, min_periods=window_large).mean()\n df['Trading Sign'] = np.where(avg_small > avg_large, 1, -1)\n df['Transaction'] = df['Trading Sign'].rolling(2).apply(lambda v: -v.prod(),\n raw=True)\n df['Daily Change'] = df.Close - df.Close.shift(1)\n df['Daily Trading Profit'] = df['Trading Sign'] * df['Daily Change']\n\n tdf = df[df.Transaction == 1].copy()\n tdf['Position'] = tdf.Close * tdf['Trading Sign']\n tdf['Profit/Loss'] = (tdf.Position * -1).rolling(2).sum()\n tdf['Winning Trades'] = np.where(tdf['Profit/Loss'] > 0, 1, 0)\n cumulative_return = tdf['Profit/Loss'].sum() / tdf.Close.iloc[0]\n winning_trades_rate = np.average(tdf['Profit/Loss'] > 0)\n n_transactions = np.sum(df.Transaction > 0)\n up_periods = np.sum(df['Daily Trading Profit'] > 0)\n down_periods = np.sum(df['Daily Trading Profit'] < 0)\n\n return {\n \"cumulative_return\": cumulative_return.item(),\n \"winning_trades_rate\": winning_trades_rate.item(),\n \"n_transactions\": n_transactions.item(),\n \"up_periods\": up_periods.item(),\n \"down_periods\": down_periods.item()\n }\n\n\ndef macd(df, window_small=12, window_large=26):\n # Calculate and define moving average of window_small periods\n avg_small = df.Close.ewm(span=window_small, min_periods=0).mean()\n\n # Calculate and define moving average of window_large periods\n avg_large = df.Close.ewm(span=window_large, min_periods=0).mean()\n\n trace_small = {\n 'x': list(df.index),\n 'y': list(avg_small),\n 'type': 'scatter',\n 'mode': 'lines',\n 'line': {\n 'width': 1,\n 'color': 'blue'\n },\n 'name': f'Moving Average of {window_small} periods'\n }\n\n trace_large = {\n 'x': list(df.index),\n 'y': list(avg_large),\n 'type': 'scatter',\n 'mode': 'lines',\n 'line': {\n 'width': 1,\n 'color': 'red'\n },\n 'name': f'Moving Average of {window_large} periods'\n }\n\n macd = avg_small - avg_large\n\n trace_macd = {\n 'name': 'MACD',\n 'x': list(df.index),\n 'y': macd,\n }\n\n avaliation = avaliate_macd(df, window_small, window_large)\n\n candle_data = {\n\n 'date': list(df.index),\n 'high': list(df.High),\n 'low': list(df.Low),\n 'open': list(df.Open),\n 'close': list(df.Close),\n };\n\n return {\n 'trace_small': trace_small,\n 'trace_large': trace_large,\n 'trace_macd': trace_macd,\n 'avaliation': avaliation,\n 'candle_data': candle_data,\n }\n\n\ndef best_macd_search(df, min_window, max_window, score_attr):\n highest_score = float('-inf')\n best_pair = None\n\n for window_small in range(min_window, max_window - 1):\n for window_large in range(window_small + 1, max_window):\n avaliation = avaliate_macd(df, window_small, window_large)\n score = avaliation[score_attr]\n\n if score > highest_score:\n highest_score = score\n best_pair = (window_small, window_large)\n\n avaliation = avaliate_macd(df, best_pair[0], best_pair[1])\n return {\n 'window_small': best_pair[0],\n 'window_large': best_pair[1],\n 'avaliation': avaliation\n }\n","repo_name":"rrbraz/trading-system-backend","sub_path":"macd.py","file_name":"macd.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16252971502","text":"from astropy.table import Table\nimport pandas\nimport os\nimport sys\nimport argparse\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy import log\n\n\ndef measure_beam(selavy_catalog, fitsfile=None):\n\n # read in the raw data\n log.info(\"Reading {}...\".format(selavy_catalog))\n data = Table.from_pandas(pandas.read_fwf(selavy_catalog, skiprows=[1,]))\n # median seems to work well\n # make sure to convert from arcsec to degrees\n BMAJ = np.median(data[\"maj_axis\"]) / 3600\n BMIN = np.median(data[\"min_axis\"]) / 3600\n BPA = np.median(data[\"pos_ang\"])\n\n log.info(\n \"Measured BMAJ = {:.1f} arcsec from {} sources\".format(BMAJ * 3600, len(data))\n )\n log.info(\n \"Measured BMIN = {:.1f} arcsec from {} sources\".format(BMIN * 3600, len(data))\n )\n log.info(\"Measured BPA = {:.1f} deg from {} sources\".format(BPA, len(data)))\n\n if fitsfile is not None:\n f = fits.open(fitsfile, mode=\"update\")\n f[0].header[\"BMAJ\"] = (BMAJ, \"Median of {}\".format(selavy_catalog))\n f[0].header[\"BMIN\"] = (BMIN, \"Median of {}\".format(selavy_catalog))\n f[0].header[\"BPA\"] = (BPA, \"Median of {}\".format(selavy_catalog))\n f.flush()\n log.info(\n \"Updated BMAJ = {:.4f} deg, BMIN = {:.4f} deg, BPA = {:.1f} deg in {}\".format(\n BMAJ, BMIN, BPA, fitsfile\n )\n )\n\n return BMAJ, BMIN, BPA\n\n\ndef main():\n log.setLevel(\"WARNING\")\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\"catalog\", type=str, help=\"Selavy catalog name\")\n parser.add_argument(\n \"-i\", \"--image\", default=None, type=str, help=\"FITS image to update\"\n )\n\n parser.add_argument(\n \"-v\", \"--verbosity\", action=\"count\", default=0, help=\"Increase output verbosity\"\n )\n\n args = parser.parse_args()\n if args.verbosity == 1:\n log.setLevel(\"INFO\")\n elif args.verbosity >= 2:\n log.setLevel(\"DEBUG\")\n\n bmaj, bmin, bpa = measure_beam(args.catalog, fitsfile=args.image)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dlakaplan/VAST_tools","sub_path":"measure_beam.py","file_name":"measure_beam.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"11890348145","text":"from flask import Blueprint, request, jsonify\nfrom model.predict import make_prediction\nfrom model.processing.data_management import load_data\nfrom model.config import config\nimport json\n\nprediction_app = Blueprint('prediction_app', __name__)\n\n_data = load_data(filename = 'test.csv')\nfeatures = _data[config.FEATURES][0:1]\n\n\n@prediction_app.route('/test', methods = ['GET'])\ndef test():\n\tif request.method == 'GET':\n\t\treturn 'living the dream!'\n\n\n\n@prediction_app.route('/predict', methods =['POST'])\ndef predict():\n\tif request.method == 'POST':\n\t\tjson_data = request.get_json()\n\t\tresults = make_prediction(input_data = json_data)\n\t\tpredictions = results.get('predictions')[0]\n\n\t\treturn jsonify({'predictions': predictions})\n\n\n\n\n\n# # make_prediction function accepts json and pass into model by converting it to dataframe\n\n# @prediction_app.route('/values', methods = ['GET'])\n# def predict():\n# \tif request.method == 'GET':\n# \t\tdata = features.to_json(orient = 'records')\n# \t\tresults = make_prediction(input_data = data)\n# \t\tpredictions = results.get('predictions')[0]\n\n# \t\treturn predictions\n","repo_name":"rohankokkula/Breast-Cancer-Project","sub_path":"ml_api/api/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"22663389452","text":"import frappe\nfrom frappe.model.document import Document\nfrom frappe import _\nfrom frappe.utils import flt, get_link_to_form\nfrom erpnext.stock.utils import get_latest_stock_qty\nfrom erpnext.healthcare.doctype.healthcare_settings.healthcare_settings import get_account\n\nclass DirectMedicationEntry(Document):\n\n\tdef validate(self):\n\t\tself.validate_patient_inpatient_record()\n\t\t\n\tdef validate_patient_inpatient_record(self):\n\t\tfor entry in self.items:\n\t\t\tif not entry.patient: \n\t\t\t\tentry.patient = self.patient\n\t\t\tif not entry.inpatient_record:\n\t\t\t\tentry.inpatient_record = self.inpatient_record\n\tdef before_submit(self):\n\t\tself.delete_zero_items()\n\n\tdef on_submit(self):\n\t\tsuccess_msg = \"\"\n\t\tif self.update_stock:\n\t\t\tstock_entry = self.process_stock()\n\t\t\tif stock_entry:\n\t\t\t\tsuccess_msg += _('Stock Entry {0} created and ').format(\n\t\t\t\t\tfrappe.bold(get_link_to_form('Stock Entry', stock_entry)))\n\t\t\t\tself.db_set(\"stock_entry\", stock_entry)\n\t\tif success_msg:\n\t\t\tfrappe.msgprint(success_msg, title=_('Success'), indicator='green')\n\t\n\tdef before_cancel(self):\n\t\tif self.stock_entry:\n\t\t\tself.cancel_stock_entry()\n\t\n\tdef cancel_stock_entry(self):\n\t\tse = frappe.get_doc(\"Stock Entry\", self.stock_entry)\n\t\tself.db_set(\"stock_entry\", None)\n\t\tse.cancel()\n\n\tdef process_stock(self):\n\t\tallow_negative_stock = frappe.db.get_single_value('Stock Settings', 'allow_negative_stock')\n\t\tif not allow_negative_stock:\n\t\t\tself.check_stock_qty()\n\n\t\treturn self.make_stock_entry()\n\n\tdef check_stock_qty(self):\n\t\tdrug_shortage = get_drug_shortage_map(self.items, self.warehouse)\n\n\t\tif drug_shortage:\n\t\t\tmessage = _('Quantity not available for the following items in warehouse {0}. ').format(frappe.bold(self.warehouse))\n\t\t\tmessage += _('Please enable Allow Negative Stock in Stock Settings or create Stock Entry to proceed.')\n\n\t\t\tformatted_item_rows = ''\n\n\t\t\tfor drug, shortage_qty in drug_shortage.items():\n\t\t\t\titem_link = get_link_to_form('Item', drug)\n\t\t\t\tformatted_item_rows += \"\"\"\n\t\t\t\t\t{0}\n\t\t\t\t\t{1}\n\t\t\t\t\"\"\".format(item_link, frappe.bold(shortage_qty))\n\n\t\t\tmessage += \"\"\"\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t{2}\n\t\t\t\t
    {0}{1}
    \n\t\t\t\"\"\".format(_('Drug Code'), _('Shortage Qty'), formatted_item_rows)\n\n\t\t\tfrappe.throw(message, title=_('Insufficient Stock'), is_minimizable=True, wide=True)\n\t\n\tdef make_stock_entry(self):\n\t\tstock_entry = frappe.new_doc('Stock Entry')\n\t\tstock_entry.purpose = 'Material Issue'\n\t\tstock_entry.set_stock_entry_type()\n\t\tstock_entry.from_warehouse = self.warehouse\n\t\tstock_entry.company = self.company\n\t\tstock_entry.direct_medication_entry = self.name\n\t\tstock_entry.patient = self.patient\n\t\tcost_center = frappe.get_cached_value('Company', self.company, 'cost_center')\n\t\texpense_account = frappe.db.get_value(\"Warehouse\", self.warehouse, \"expense_account\")\n\n\t\tfor entry in self.items:\n\t\t\tif frappe.db.get_value(\"Item\", entry.item_code, \"is_stock_item\"):\n\t\t\t\tse_child = stock_entry.append('items')\n\t\t\t\tse_child.item_code = entry.item_code\n\t\t\t\tse_child.item_name = entry.item_name\n\t\t\t\tse_child.uom = frappe.db.get_value('Item', entry.item_code, 'stock_uom')\n\t\t\t\tse_child.stock_uom = se_child.uom\n\t\t\t\tse_child.qty = flt(entry.qty)\n\t\t\t\t# in stock uom\n\t\t\t\tse_child.conversion_factor = 1\n\t\t\t\tse_child.cost_center = cost_center\n\t\t\t\t# references\n\t\t\t\tse_child.patient = entry.patient\n\t\t\t\tse_child.expense_account = expense_account\n\t\tif stock_entry.get(\"items\"):\n\t\t\tstock_entry.insert()\n\t\t\tstock_entry.submit()\n\t\t\treturn stock_entry.name\n\t\treturn None\n\n\tdef check_invoiced(self):\n\t\tself.invoiced = True\n\t\tfor i in self.items:\n\t\t\tif not i.invoiced:\n\t\t\t\tself.invoiced = False\n\t\t\t\tbreak\n\t\tself.db_update()\n\n\t@frappe.whitelist()\n\tdef item_code_query(self):\n\t\tres = frappe.get_all(\"Bin\", filters = {\"warehouse\": self.warehouse}, pluck = \"item_code\")\n\t\tres += frappe.get_all(\"Item\", filters = {\"is_stock_item\": 0}, pluck = \"name\")\n\n\tdef delete_zero_items(self):\n\t\titems = []\n\t\tfor item in self.items:\n\t\t\tif item.qty:\n\t\t\t\titems.append(item)\n\t\t\tself.items = items\n\ndef get_drug_shortage_map(medication_orders, warehouse):\n\t\"\"\"\n\t\tReturns a dict like { item_code: shortage_qty }\n\t\"\"\"\n\tdrug_requirement = dict()\n\tfor d in medication_orders:\n\t\tif frappe.db.get_value(\"Item\", d.item_code, \"is_stock_item\"):\n\t\t\tif not drug_requirement.get(d.item_code):\n\t\t\t\tdrug_requirement[d.item_code] = 0\n\t\t\tdrug_requirement[d.item_code] += flt(d.qty)\n\n\tdrug_shortage = dict()\n\tfor drug, required_qty in drug_requirement.items():\n\t\tavailable_qty = get_latest_stock_qty(drug, warehouse)\n\t\tif flt(required_qty) > flt(available_qty):\n\t\t\tdrug_shortage[drug] = flt(flt(required_qty) - flt(available_qty))\n\n\treturn drug_shortage\n\n","repo_name":"Pivottech/erpnext-omaya","sub_path":"erpnext/healthcare/doctype/direct_medication_entry/direct_medication_entry.py","file_name":"direct_medication_entry.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"13036072949","text":"import os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport keras.backend as K\r\nimport keras\r\nimport cv2\r\n\r\nfrom keras.models import load_model\r\n\r\ndef grad_cam(model, category_index, layer_name):\r\n print(layer_name)\r\n\r\n inp = model.input\r\n y_c = model.output.op.inputs[0][0, category_index]\r\n A_k = model.get_layer(layer_name).output\r\n print(y_c, A_k)\r\n\r\n get_output = K.function(\r\n [inp], [A_k, K.gradients(y_c, A_k)[0], model.output])\r\n\r\n return get_output\r\n\r\n\r\ndef apply_grad_cam(get_output, input):\r\n input_image = input[0]\r\n\r\n [conv_output, grad_val, model_output] = get_output(input)\r\n\r\n conv_output = conv_output[0]\r\n grad_val = grad_val[0]\r\n\r\n weights = np.mean(grad_val, axis=(0, 1))\r\n\r\n grad_cam = np.zeros(dtype=np.float32, shape=conv_output.shape[0:2])\r\n for k, w in enumerate(weights):\r\n grad_cam += w * conv_output[:, :, k]\r\n\r\n grad_cam = np.maximum(grad_cam, 0)\r\n heatmap = grad_cam/np.max(grad_cam)\r\n\r\n image = input_image.squeeze()\r\n image -= np.min(image)\r\n image = 255 * image / np.max(image)\r\n image1 = cv2.resize(cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_GRAY2RGB), (240, 1460),\r\n interpolation=cv2.INTER_NEAREST)\r\n\r\n print(np.percentile(heatmap/np.max(heatmap), [0, 25, 50, 75, 100]))\r\n heatmap1 = cv2.resize(heatmap/np.max(heatmap),\r\n (240, 1460), interpolation=cv2.INTER_LINEAR)\r\n\r\n grad_cam = cv2.applyColorMap(np.uint8(255*heatmap1), cv2.COLORMAP_JET)\r\n grad_cam = np.float32(grad_cam) + np.float32(image1)\r\n grad_cam = 255 * grad_cam / np.max(grad_cam)\r\n\r\n return np.uint8(grad_cam), heatmap\r\n\r\n\r\npca_exp = pd.read_excel(\"data/PCA_EXP.xlsx\", header=None)\r\npca_cnv = pd.read_excel(\"data/PCA_CNV.xlsx\", header=None)\r\npca_mt = pd.read_excel(\"data/PCA_MT.xlsx\", header=None)\r\nclinical = pd.read_excel(\"data/Clinical.xlsx\")\r\n\r\n# data size: 146 pathways, 5 PCs\r\nn = len(pca_exp) # sample size: number of Pts\r\npath_n = 146 # number of pathways\r\npc = 5 # number of PCs\r\n\r\n# data creation-EXP\r\npca_exp = pca_exp.to_numpy()\r\nprint(pca_exp.shape)\r\nexp_data = np.zeros((n, path_n, pc))\r\nfor i in range(n):\r\n for j in range(path_n):\r\n exp_data[i, j, :] = pca_exp[i, j * pc:(j + 1) * pc]\r\n\r\n# data creation-CNV\r\npca_cnv = pca_cnv.to_numpy()\r\ncnv_data = np.zeros((n, path_n, pc))\r\nfor i in range(n):\r\n for j in range(path_n):\r\n cnv_data[i, j, :] = pca_cnv[i, j * pc:(j + 1) * pc]\r\n\r\n# data creation-MT\r\npca_mt = pca_mt.to_numpy()\r\nmt_data = np.zeros((n, path_n, pc))\r\nfor i in range(n):\r\n for j in range(path_n):\r\n mt_data[i, j, :] = pca_mt[i, j * pc:(j + 1) * pc]\r\n\r\n# data merge: mRNA expression, CNV, and MT with a specific number of PCs\r\nno_pc = 2 # use the first 2 PCs among 5 PCs\r\nall_data = np.zeros((n, path_n, no_pc * 3))\r\nfor i in range(n):\r\n all_data[i, :, :] = np.concatenate((exp_data[i, :, 0:no_pc], cnv_data[i, :, 0:no_pc], mt_data[i, :, 0:no_pc]),\r\n axis=1)\r\n\r\nindex = np.arange(0, pca_exp.shape[1], pc)\r\n\r\nclinical = clinical.to_numpy()\r\nsurvival = clinical[:, 5]\r\nos_months = clinical[:, 6]\r\nidx0 = np.where((survival == 1) & (os_months <= 24)) # class0\r\nidx1 = np.where(os_months > 24) # class1\r\n\r\nall_data = all_data[:, :, :]\r\n\r\ndata_0 = all_data[idx0, :, :]\r\ndata_0 = data_0[0, :, :, :]\r\ndata_1 = all_data[idx1, :, :]\r\ndata_1 = data_1[0, :, :, :]\r\n\r\noutcomes_0 = np.zeros(len(idx0[0]))\r\noutcomes_1 = np.ones(len(idx1[0]))\r\n\r\n# data merge\r\ndata = np.concatenate((data_0, data_1))\r\noutcomes = np.concatenate((outcomes_0, outcomes_1))\r\n\r\nprint('test')\r\nevent_rate = np.array(\r\n [outcomes_0.shape[0], outcomes_1.shape[0]])/outcomes_0.shape[0]\r\nprint(event_rate)\r\n\r\nvmin = -10\r\nvmax = 10\r\nm = 1\r\n\r\nmodel_file = 'PathCNN_model.h5'\r\n\r\nmodel = load_model(model_file)\r\nlayers = model.layers\r\nprint(model.summary())\r\n\r\norig_weights = model.get_weights().copy()\r\n\r\noutput_layer = model.get_layer('dense_2')\r\noutput_weights = output_layer.get_weights()\r\nprint(output_weights[1])\r\n\r\ncol = ['outcome', 'prediction', 'target_class',\r\n 'probability']+list(range(1, no_pc*path_n*3+1))\r\nprint(col)\r\n\r\nlayer = layers[4] # the last layer before flatten\r\nprint(layer.name)\r\nweights = layer.get_weights()\r\n\r\nget_output = [None, None]\r\nfor target_class in range(2):\r\n get_output[target_class] = grad_cam(model, target_class, layer.name)\r\n\r\nos.makedirs('output/'+layer.name, exist_ok=True)\r\nfor i in range(0, data.shape[0], 1):\r\n oimg = data[i, :, :]\r\n\r\n print(f'\\ncase {i:03d}_{outcomes[i]:.0f}')\r\n print(oimg.shape)\r\n\r\n img = ((np.clip(oimg, vmin, vmax) - vmin) /\r\n (vmax - vmin) * 255).astype('uint8')\r\n\r\n timg = oimg.reshape(1, oimg.shape[0], oimg.shape[1], 1)\r\n\r\n preprocessed_input = [timg]\r\n\r\n model.set_weights(orig_weights)\r\n predictions = model.predict(preprocessed_input)\r\n print('Predicted class:')\r\n print(predictions)\r\n predicted_class = np.argmax(predictions)\r\n print(predicted_class)\r\n \r\n for target_class in range(2):\r\n gradcam, heatmap = apply_grad_cam(get_output[target_class], preprocessed_input)\r\n filename = f'output/{layer.name}/gradcam{i:03d}_{outcomes[i]:.0f}_{predicted_class:d}_{target_class:d}_{predictions[0][target_class]:0.2f}.png'\r\n cv2.imwrite(filename, gradcam)\r\n\r\n heatmap1 = cv2.resize(heatmap, (no_pc*3, path_n))\r\n #print(heatmap.shape)\r\n data_row = [[outcomes[i], predicted_class, target_class,\r\n predictions[0][target_class]]+heatmap1.flatten().tolist()]\r\n gradcam_pd = pd.DataFrame(data_row, columns=col, index=[i])\r\n if i == 0 and target_class == 0:\r\n gradcam_pd.to_csv(\r\n f'output/{layer.name}/pathcnn_gradcam.csv', mode='w')\r\n else:\r\n gradcam_pd.to_csv(f'output/{layer.name}/pathcnn_gradcam.csv',\r\n mode='a', header=False)\r\n","repo_name":"mskspi/PathCNN","sub_path":"PathCNN_GradCAM.py","file_name":"PathCNN_GradCAM.py","file_ext":"py","file_size_in_byte":5930,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"80"} +{"seq_id":"73030788097","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division, absolute_import, unicode_literals\n\nimport csv\nfrom itertools import chain\n\nfrom tangible import scales\nfrom tangible.shapes.bars import BarsND\nfrom tangible.backends.openscad import OpenScadBackend\n\n\n# Read data into list\ndatapoints = [list() for i in range(9)]\nwith open('analytics-full-13.csv', 'r') as datafile:\n reader = csv.DictReader(datafile)\n for row in reader:\n date = row['Day']\n month = int(date.split('/', 1)[0])\n visits = int(row['Visits'])\n datapoints[month - 1].append(visits)\n\n\n# Normalize data\nall_datapoints = list(chain.from_iterable(datapoints))\nscale = scales.linear([min(all_datapoints), max(all_datapoints)], [10, 150])\ndatapoints = [[scale(i) for i in x] for x in datapoints]\n\n# Create shape\nbars = BarsND(datapoints, bar_width=7, bar_depth=7, center_layers=False)\n\ncode = bars.render(backend=OpenScadBackend)\nprint(code)\n","repo_name":"dbrgn/tangible","sub_path":"examples/barsnd.py","file_name":"barsnd.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"80"} +{"seq_id":"17135883295","text":"import bpy\nimport sys\n#import mathutils\nfrom mathutils import *\nimport bgl\nimport blf\nimport gpu\nfrom gpu_extras.batch import batch_for_shader\nfrom ..math.vecmath import *\n\nfrom enum import Enum\n\nfrom .graphics import DrawContext2D\nfrom .layout import *\nfrom .panel import *\nfrom .label import *\nfrom .events import *\n\n#----------------------------------\n\n# class Inset2D:\n # def __init__(self, left = 0, top = 0, right = 0, bottom = 0):\n # self.left = left\n # self.top = top\n # self.right = right\n # self.bottom = bottom\n \n # def __str__(self):\n # return str(self.left) + \", \" + str(self.top) + \", \" + str(self.right) + \", \" + str(self.bottom)\n \n\n\n\n\n\n#----------------------------------\n\nclass FoldoutPanel(Panel):\n def __init__(self):\n super().__init__()\n self.position = Vector((0, 0))\n\n\n\n#----------------------------------\n\nclass TitleBar(Label):\n def __init__(self, window):\n super().__init__()\n self.window = window\n self.dragging = False\n\n\n def mouse_pressed(self, event):\n if event.mouse_button == MouseButton.LEFT:\n self.dragging = True\n self.drag_start = event.screen_pos\n self.window_start = self.window.position.copy()\n\n # print (\"TextINput pressed\")\n # print(\"event.pos\" + str(event.pos))\n # print(\"event.screen_pos\" + str(event.screen_pos))\n return True\n \n def mouse_released(self, event):\n if event.mouse_button == MouseButton.LEFT:\n self.dragging = False\n\n # print (\"TextINput released\")\n # print(\"event.pos\" + str(event.pos))\n # print(\"event.screen_pos\" + str(event.screen_pos))\n return True\n \n def mouse_dragged(self, event):\n if self.dragging:\n offset = event.screen_pos - self.drag_start\n self.window.position = self.window_start + offset\n \n return True\n\n\n # def mouse_click(self, context, event):\n # c2s = self.coords_to_screen_matrix(context)\n # s2c = c2s.inverted()\n # mouse_pos = s2c @ Vector((event.mouse_region_x, event.mouse_region_y, 0, 1))\n\n # # print (\"event.mouse_region_x \" + str(event.mouse_region_x))\n # # print (\"event.mouse_region_y \" + str(event.mouse_region_y))\n # # print (\"mouse_pos \" + str(mouse_pos))\n \n # bounds = self.bounds()\n \n # # print (\"bounds \" + str(bounds))\n \n # if bounds.contains(mouse_pos.x, mouse_pos.y):\n # if event.value == \"PRESS\":\n # self.layout.dispatch_mouse_event\n \n # self.dragging = True\n # self.mouse_down_pos = mouse_pos\n # self.start_position = self.position.copy()\n # else:\n # self.dragging = False\n# # return {'consumed': True}\n # return True\n \n# # return {'consumed': False}\n # return False\n \n # def mouse_move(self, context, event):\n # c2s = self.coords_to_screen_matrix(context)\n # s2c = c2s.inverted()\n # mouse_pos = s2c @ Vector((event.mouse_region_x, event.mouse_region_y, 0, 1))\n \n \n # if self.dragging:\n # offset = mouse_pos - self.mouse_down_pos\n \n # self.position = self.start_position + offset.to_2d()\n# # return {'consumed': True}\n # return True\n \n# # return {'consumed': False}\n # return False\n \n\n#----------------------------------\n\nclass PanelStack:\n def __init__(self, stack):\n self.stack = stack\n \n # def add(self, panel):\n # self.stack.append(panel)\n \n def window_to_local(self, window_pos):\n local_pos = window_pos.copy()\n for panel in self.stack:\n local_pos -= panel.position\n return local_pos\n\n def __str__(self):\n strn = \"\"\n for panel in self.stack:\n strn += \"panel bounds \" + str(panel.bounds()) + \"\\n\"\n return strn\n\n#----------------------------------\n\nclass Window:\n def __init__(self):\n self.position = Vector((100, 40))\n self.size = Vector((200, 400))\n\n self.background_color = Vector((.5, .5, .5, 1))\n self.font_color = Vector((1, 1, 1, 1))\n self.font_dpi = 20\n self.font_size = 60\n \n self.dragging = False\n \n self.layout = LayoutBox(Axis.Y)\n self.layout.set_window(self)\n\n self.title_panel = TitleBar(self)\n self.layout.add_child(self.title_panel)\n self.title_panel.set_font_size(60)\n \n self.main_panel = Panel()\n self.layout.add_child(self.main_panel)\n self.main_panel.expansion_type_x = ExpansionType.EXPAND\n self.main_panel.expansion_type_y = ExpansionType.EXPAND\n \n\n self.layout.layout_components(self.bounds())\n \n #Track mouse press events\n self.captured_panel_stack = None\n self.mouse_left_down = False\n self.mouse_middle_down = False\n self.mouse_right_down = False\n\n\n def get_title(self):\n return self.__title\n\n def set_title(self, title):\n self.__title = title\n self.title_panel.text = title\n\n def get_main_panel(self):\n return self.main_panel\n\n def get_screen_position(self):\n return self.position.copy()\n \n def bounds(self):\n return Rectangle2D(self.position.x, self.position.y, self.size.x, self.size.y)\n \n def coords_to_screen_matrix(self, context):\n region = context.region\n #rv3d = context.region_data\n\n mT = Matrix.Translation((0, region.height, 0))\n mS = Matrix.Diagonal((1, -1, 1, 1))\n return mT @ mS\n \n \n def draw(self, context):\n bgl.glDisable(bgl.GL_DEPTH_TEST)\n \n ctx = DrawContext2D(context)\n \n ctx.translate(self.position.x, self.position.y)\n ctx.color = self.background_color.copy()\n ctx.fill_round_rectangle(0, 0, self.size.x, self.size.y, 10)\n\n #Draw panel components\n self.layout.draw(ctx)\n\n \n def mouse_pos(self, context, event):\n c2s = self.coords_to_screen_matrix(context)\n s2c = c2s.inverted()\n screen_pos = s2c @ Vector((event.mouse_region_x, event.mouse_region_y, 0, 1))\n return screen_pos.to_2d()\n \n def window_to_local(self, window_pos):\n local_pos = window_pos.copy()\n for panel in stack:\n local_pos -= panel.position\n return local_pos\n \n def handle_event(self, context, event):\n bounds = self.bounds()\n\n# print(\"event typ:\" + event.type + \" val: \" + event.value)\n\n mouse_button = None\n \n if event.type == 'LEFTMOUSE':\n mouse_button = MouseButton.LEFT\n \n if event.value == \"PRESS\":\n self.mouse_left_down = True\n elif event.value == \"RELEASE\":\n self.mouse_left_down = False\n\n if event.type == 'RIGHTMOUSE':\n mouse_button = MouseButton.RIGHT\n \n if event.value == \"PRESS\":\n self.mouse_right_down = True\n elif event.value == \"RELEASE\":\n self.mouse_right_down = False\n\n if event.type == 'MIDDLEMOUSE':\n mouse_button = MouseButton.MIDDLE\n \n if event.value == \"PRESS\":\n self.mouse_middle_down = True\n elif event.value == \"RELEASE\":\n self.mouse_middle_down = False\n\n\n if mouse_button != None:\n mouse_pos = self.mouse_pos(context, event)\n mouse_window_pos = mouse_pos - self.position\n \n if self.captured_panel_stack != None:\n \n # print(\"panel stack is captured\")\n \n if event.value == \"RELEASE\":\n# print(\"RELEASE stack \\n\" + str(self.captured_panel_stack))\n \n local_pos = self.captured_panel_stack.window_to_local(mouse_window_pos)\n evt = MouseButtonEvent(\n mouse_button = mouse_button, \n pos = local_pos, \n screen_pos = mouse_pos,\n left_down = self.mouse_left_down,\n middle_down = self.mouse_middle_down,\n right_down = self.mouse_right_down,\n shift_down = event.shift,\n ctrl_down = event.ctrl,\n alt_down = event.alt\n )\n \n self.captured_panel_stack.stack[-1].mouse_released(evt)\n \n# print(\"self.mouse_left_down\" + str(self.mouse_left_down))\n# print(\"self.mouse_right_down\" + str(self.mouse_right_down))\n \n #If all buttons are released, end mouse capture\n if self.mouse_left_down == False and self.mouse_middle_down == False and self.mouse_right_down == False:\n# print(\"END capture\")\n self.captured_panel_stack = None\n \n return True\n \n elif bounds.contains(mouse_pos[0], mouse_pos[1]):\n #evt = MouseButtonEvent(mouse_button = MouseButton.LEFT, pos = mouse_pos - self.position, screen_pos = mouse_pos)\n\n if event.value == \"PRESS\":\n stack = self.layout.pick_panel_stack(mouse_window_pos)\n self.captured_panel_stack = PanelStack(stack)\n \n \n# print(\"self.captured_panel_stack \\n\" + str(self.captured_panel_stack))\n \n local_pos = self.captured_panel_stack.window_to_local(mouse_window_pos)\n evt = MouseButtonEvent(\n mouse_button = mouse_button, \n pos = local_pos, \n screen_pos = mouse_pos,\n left_down = self.mouse_left_down,\n middle_down = self.mouse_middle_down,\n right_down = self.mouse_right_down,\n shift_down = event.shift,\n ctrl_down = event.ctrl,\n alt_down = event.alt\n )\n self.captured_panel_stack.stack[-1].mouse_pressed(evt)\n \n return True\n \n \n elif event.type == 'MOUSEMOVE':\n mouse_pos = self.mouse_pos(context, event)\n mouse_window_pos = mouse_pos - self.position\n \n if self.captured_panel_stack != None:\n# print(\"mouse DRAG\")\n local_pos = self.captured_panel_stack.window_to_local(mouse_window_pos)\n evt = MouseButtonEvent(\n pos = local_pos, \n screen_pos = mouse_pos,\n left_down = self.mouse_left_down,\n middle_down = self.mouse_middle_down,\n right_down = self.mouse_right_down,\n shift_down = event.shift,\n ctrl_down = event.ctrl,\n alt_down = event.alt\n )\n \n self.captured_panel_stack.stack[-1].mouse_dragged(evt)\n \n return True\n \n elif bounds.contains(mouse_pos[0], mouse_pos[1]):\n# print(\"mouse MOVE\")\n stack = self.layout.pick_panel_stack(mouse_window_pos)\n stack = PanelStack(stack)\n \n local_pos = stack.window_to_local(mouse_window_pos)\n evt = MouseButtonEvent(\n pos = local_pos, \n screen_pos = mouse_pos,\n left_down = self.mouse_left_down,\n middle_down = self.mouse_middle_down,\n right_down = self.mouse_right_down,\n shift_down = event.shift,\n ctrl_down = event.ctrl,\n alt_down = event.alt\n )\n stack.stack[-1].mouse_moved(evt)\n \n return True\n \n return False\n \n ","repo_name":"blackears/blenderTerrainSculpt","sub_path":"lib/kitfox/gui/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":12415,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"80"} +{"seq_id":"39938547839","text":"temp=[int(x) for x in input().split(' ')]\nn=temp[0]\nm=temp[1]\ntemp=[int(x) for x in input().split(' ')]\nt=temp.copy()\nfor i in range(m):\n pre=[int(x) for x in input().split(' ')]\n l=pre[1]\n r=pre[2]\n now=temp[l-1:r]\n if(pre[0]==0):\n now.sort()\n else:\n now.sort(reverse=True)\n temp=temp[:l-1]+now+temp[r:]\n \nq=int(input())\nprint(temp[q-1])","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2387/60777/287818.py","file_name":"287818.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"72358706497","text":"#@+leo-ver=5-thin\n#@+node:edream.110203113231.734: * @file quit_leo.py\n\"\"\" Shows how to force Leo to quit.\"\"\"\n\n#@@language python\n#@@tabwidth -4\n\nimport leo.core.leoGlobals as g\n\n__version__ = \"1.2\"\n\ndef init():\n\n ok = not g.app.unitTesting # Not for unit testing.\n\n if ok:\n def forceLeoToQuit(tag,keywords):\n if not g.app.initing:\n g.pr(\"forceLeoToQuit\",tag)\n g.app.forceShutdown()\n\n # Force a shutdown at any other time, even \"idle\" time.\n # Exception: do not call g.app.forceShutdown in a \"start2\" hook.\n g.pr(__doc__)\n g.registerHandler(\"idle\",forceLeoToQuit)\n g.plugin_signon(__name__)\n\n return ok\n#@-leo\n","repo_name":"chiamingyen/portable_leoeditor","sub_path":"data/Python33/Lib/site-packages/leo/plugins/quit_leo.py","file_name":"quit_leo.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"9909849281","text":"\nshops = {\n 'ашан':\n [\n {'name': 'печенье', 'price': 10.99},\n {'name': 'конфеты', 'price': 34.99},\n {'name': 'карамель', 'price': 45.99},\n {'name': 'пирожное', 'price': 67.99}\n ],\n 'пятерочка':\n [\n {'name': 'печенье', 'price': 9.99},\n {'name': 'конфеты', 'price': 32.99},\n {'name': 'карамель', 'price': 46.99},\n {'name': 'пирожное', 'price': 59.99}\n ],\n 'магнит':\n [\n {'name': 'печенье', 'price': 11.99},\n {'name': 'конфеты', 'price': 30.99},\n {'name': 'карамель', 'price': 41.99},\n {'name': 'пирожное', 'price': 62.99}\n ],\n}\n\n\nsweets = {\n 'печенье': [\n {'shop': 'пятерочка', 'price': 9.99},\n {'shop': 'ашан', 'price': 10.99},\n\n ],\n \"конфеты\": [\n {'shop': 'пятерочка', 'price': 32.99},\n {'shop': 'магнит', 'price': 30.99}\n ],\n \"пирожное\": [\n {'shop': 'пятерочка', 'price': 59.99},\n {'shop': 'магнит', 'price': 62.99}\n ],\n 'карамель': [\n {'shop': 'ашан', 'price': 45.99},\n {'shop': 'магнит', 'price': 41.99}\n ]}\nprint(sweets)\n\n","repo_name":"Masterartem/probe","sub_path":"Lesson_002/09_shopping.py","file_name":"09_shopping.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"4951073686","text":"class Solution:\n def missingElement(self, nums: List[int], k: int) -> int:\n n=len(nums)\n left=0\n right=n-1\n \n noOfMissingNumsInList=nums[right]-nums[left]-(right-left)\n \n if noOfMissingNumsInList=k:\n right=mid\n else:\n k-=noOfMissingNumsBtwLM\n left=mid\n \n return nums[left]+k","repo_name":"sonalsrivas/Leetcode-Solutions---Python---Java","sub_path":"1060-missing-element-in-sorted-array/1060-missing-element-in-sorted-array.py","file_name":"1060-missing-element-in-sorted-array.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"16919534670","text":"def get_top(lst):\r\n k = 3\r\n if k > (len(lst)/2):\r\n top_min = lst[0:k]\r\n for i in range(k,len(lst)):\r\n for n in range(len(top_min)-1,0,-1):\r\n if top_min[n] > top_min[n-1]:\r\n ch_ = top_min[n]\r\n top_min[n] = top_min[n-1]\r\n top_min[n-1] = ch_\r\n if lst[i] < top_min[0]:\r\n top_min[0] = lst[i]\r\n return max(top_min)\r\n else:\r\n k = len(lst) - k + 1\r\n top_max = lst[0:k]\r\n for i in range(k,len(lst)):\r\n for n in range(len(top_max)-1,0,-1):\r\n if top_max[n] < top_max[n-1]:\r\n ch_ = top_max[n]\r\n top_max[n] = top_max[n-1]\r\n top_max[n-1] = ch_\r\n if lst[i] > top_max[0]:\r\n top_max[0] = lst[i]\r\n return min(top_max) \r\n\r\nprint(get_top([73,188,894,915,940,616,900,548]))","repo_name":"vlsilver/i_python","sub_path":"py-Kth smallest element-2 .py","file_name":"py-Kth smallest element-2 .py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"80"} +{"seq_id":"23264725500","text":"import logging\nimport numpy as np\nimport pandas as pd\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OrdinalEncoder, OneHotEncoder, FunctionTransformer\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n\ndef delta_date_feature(dates):\n \"\"\"\n Given a 2d array containing dates (in any format recognized by pd.to_datetime), it returns the delta in days\n between each date and the most recent date in its column\n \"\"\"\n date_sanitized = pd.DataFrame(dates).apply(pd.to_datetime)\n return date_sanitized.apply(lambda d: (d.max() - d).dt.days, axis=0).to_numpy()\n\n\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)-15s %(message)s\")\nlogger = logging.getLogger()\n\n\ndef get_inference_pipeline(rf_config, max_tfidf_features):\n # Let's handle the categorical features first\n # Ordinal categorical are categorical values for which the order is meaningful, for example\n # for room type: 'Entire home/apt' > 'Private room' > 'Shared room'\n ordinal_categorical = [\"room_type\"]\n non_ordinal_categorical = [\"neighbourhood_group\"]\n # NOTE: we do not need to impute room_type because the type of the room\n # is mandatory on the websites, so missing values are not possible in production\n # (nor during training). That is not true for neighbourhood_group\n ordinal_categorical_preproc = OrdinalEncoder()\n\n ######################################\n # Build a pipeline with two steps:\n # 1 - A SimpleImputer(strategy=\"most_frequent\") to impute missing values\n # 2 - A OneHotEncoder() step to encode the variable\n non_ordinal_categorical_preproc = make_pipeline(\n SimpleImputer(strategy=\"most_frequent\"),\n OneHotEncoder()\n )\n ######################################\n\n # Let's impute the numerical columns to make sure we can handle missing values\n # (note that we do not scale because the RF algorithm does not need that)\n float_imputed = [\n \"reviews_per_month\",\n ]\n float_imputer = make_pipeline(\n SimpleImputer(strategy=\"constant\", fill_value=0.0),\n )\n\n int_imputed = [\n \"minimum_nights\",\n \"number_of_reviews\",\n \"calculated_host_listings_count\",\n \"availability_365\"\n ]\n int_imputer = make_pipeline(\n SimpleImputer(strategy=\"constant\", fill_value=0)\n )\n\n # A MINIMAL FEATURE ENGINEERING step:\n # we create a feature that represents the number of days passed since the last review\n # First we impute the missing review date with an old date (because there hasn't been\n # a review for a long time), and then we create a new feature from it,\n date_imputer = make_pipeline(\n SimpleImputer(missing_values=None, strategy='constant', fill_value='2010-01-01'),\n FunctionTransformer(delta_date_feature, check_inverse=False, validate=False)\n )\n\n # Some minimal NLP for the \"name\" column\n reshape_to_1d = FunctionTransformer(np.reshape, kw_args={\"newshape\": -1})\n name_tfidf = make_pipeline(\n SimpleImputer(missing_values=None, strategy=\"constant\", fill_value=\"imputed name\"),\n reshape_to_1d,\n TfidfVectorizer(\n binary=False,\n max_features=max_tfidf_features,\n stop_words='english'\n )\n )\n\n # Let's put everything together\n preprocessor = ColumnTransformer(\n transformers=[\n (\"ordinal_cat\", ordinal_categorical_preproc, ordinal_categorical),\n (\"non_ordinal_cat\", non_ordinal_categorical_preproc, non_ordinal_categorical),\n (\"impute_float\", float_imputer, float_imputed),\n (\"impute_int\", int_imputer, int_imputed),\n (\"transform_date\", date_imputer, [\"last_review\"]),\n (\"transform_name\", name_tfidf, [\"name\"])\n ],\n remainder=\"drop\", # This drops the columns that we do not transform\n )\n\n processed_features = ordinal_categorical + \\\n non_ordinal_categorical + \\\n float_imputed + \\\n int_imputed + \\\n [\"last_review\", \"name\"]\n\n # Create random forest\n random_forest = RandomForestRegressor(**rf_config)\n\n ######################################\n # Create the inference pipeline. The pipeline must have 2 steps: a step called \"preprocessor\" applying the\n # ColumnTransformer instance that we saved in the `preprocessor` variable, and a step called \"random_forest\"\n # with the random forest instance that we just saved in the `random_forest` variable.\n # HINT: Use the explicit Pipeline instead of make_pipeline constructor to leverage named step\n sk_pipe = Pipeline(\n steps=[\n (\"preprocessor\", preprocessor),\n (\"random_forest\", random_forest)\n ]\n )\n\n return sk_pipe, processed_features\n","repo_name":"iahsanujunda/nyc_airbnb_pipeline","sub_path":"nyc_airbnb/utils/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"33197752159","text":"import ply.ply.lex as lex\nimport ply.ply.yacc as yacc\nfrom .script import lexer as compile_lexer\nfrom .script import syntax as compile_syntax\nfrom .script import preparser\n\nimport json\nimport os\n\n\nclass Graph(object):\n\n def __init__(self, script_text, method_registry, logger, conf_paths=None):\n self.method_registry = method_registry\n self.logger = logger\n self.conf_paths = conf_paths\n if not self.conf_paths:\n self.conf_paths = []\n\n self.node_map = {}\n self.conf_map = {}\n self.__conf_gen_list__ = []\n # to record the last loading time stamp for each conf file\n self.conf_update_ts = {}\n self.__load_confs__()\n\n lexer = lex.lex(module=compile_lexer)\n syntax = yacc.yacc(module=compile_syntax)\n syntax.__define_node__ = self.__define_node__\n if logger:\n syntax.__logger__ = logger\n\n parser = preparser.Parser()\n for c in script_text:\n parser.feed(c)\n parser.close()\n self.logger.warning('final shuvi script[%s]' % parser.get_final_script())\n syntax.parse(parser.get_final_script(), lexer=lexer)\n\n def run(self, sess, outputpath):\n nodename, outputname = outputpath.split('.')\n node = self.node_map.get(nodename, None)\n if node == None:\n self.logger.error('node of name[%s] not found' % nodename)\n return None\n return node.run(sess, outputname)\n\n def init(self, sess, tf_initializer):\n sess.run(tf_initializer)\n for name, node in self.node_map.items():\n node.init(sess)\n\n def conf(self):\n if self.__load_confs__():\n for name, node in self.node_map.items():\n node.conf(self.conf_map, self.conf_map.get(name, None))\n\n def gen_conf(self, out_path):\n with open(out_path, 'w+') as _f:\n _f.write('\\n'.join(['{'] + ['\"%s\":%s,' % (name, json.dumps(conf, indent=4)) for name, conf in self.__conf_gen_list__] + ['\"conf_end_flag\": \"pls remove it\"\\n}']))\n\n def get_output(self, outputpath):\n nodename, outputname = outputpath.split('.')\n node = self.node_map.get(nodename, None)\n if node is None:\n self.logger.error('node of name[%s] not found' % nodename)\n return None\n return node.get_output(outputname)\n\n # private\n def __define_node__(self, nodename, methodname, outputs, placeholders, inputs):\n if methodname not in self.method_registry:\n self.logger.error('method name[%s] not registed' % methodname)\n if nodename in self.node_map:\n self.logger.error('node[%s] has already registed' % nodename)\n\n input_edge_list, input_node_list = [], set()\n for input_node_name, input_edge_name in inputs:\n input_node = self.node_map.get(input_node_name, None)\n if input_node is None:\n self.logger.error('undefined node[%s]' % input_node_name)\n input_edge = input_node.get_output(input_edge_name)\n if input_edge is None:\n self.logger.error('undefined edge[%s] of node[%s]' % (input_edge_name, input_node_name))\n input_node_list.add(input_node)\n input_edge_list.append(input_edge)\n\n node = self.method_registry[methodname](self,\n input_edge_list,\n list(input_node_list),\n self.conf_map,\n self.conf_map.get(nodename, None),\n self.logger)\n node.post_construct()\n \n self.__verify_outputs__(node, outputs)\n self.__verify_placeholders__(node, placeholders)\n\n # generate conf\n node_conf_to_gen = {}\n for conf_name, dft_val in node.list_conf_name():\n node_conf_to_gen[conf_name] = dft_val\n self.__conf_gen_list__.append((nodename, node_conf_to_gen))\n\n # register node\n self.node_map[nodename] = node\n\n def __load_confs__(self):\n has_updated = False\n for conf_path in self.conf_paths:\n try:\n cur_ts = os.path.getmtime(conf_path)\n if conf_path not in self.conf_update_ts or self.conf_update_ts[conf_path] != cur_ts:\n with open(conf_path) as i_f:\n js = json.loads(i_f.read())\n for k in js:\n self.conf_map[k] = js[k]\n self.conf_update_ts[conf_path] = cur_ts\n has_updated = True\n except Exception as e:\n self.logger.warning('catch exception when loading conf file[%s]: %s' % (conf_path, str(e)))\n return has_updated\n\n @staticmethod\n def __verify_outputs__(node, names):\n for name in names:\n node.get_output(name)\n\n @staticmethod\n def __verify_placeholders__(node, names):\n for name in names:\n node.get_placeholder(name)\n\n","repo_name":"GiftiaCoder/shuviscript","sub_path":"shuvi/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"7050293195","text":"import torch\nfrom .barycenter import *\n\n\ndef pca(P, dim=0):\n \"\"\"\n Returns the principal component analysis of the given input set\n\n Parameters\n ----------\n P : Tensor\n the input point set tensor\n dim : int (optional)\n the dimension along the pca is computed\n\n Returns\n -------\n (Tensor,Tensor)\n the barycenter of the point set and its principal directions in matrix form\n \"\"\"\n\n B = barycenter(P, dim=dim)\n p = P-B\n C = torch.mm(torch.t(p), p)\n U, S, V = torch.svd(C)\n return B, torch.t(V)\n","repo_name":"mauriziokovacic/ACME","sub_path":"ACME/geometry/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"80"} +{"seq_id":"42507132085","text":"from flask import Flask, render_template, request\nimport json\nimport pandas as pd\n\napp = Flask(__name__)\ndata=pd.read_csv('monthly_electricity_source_data.csv')\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n@app.route(\"/button1\", methods=['POST'])\ndef button1():\n print(request.form['status'])\n return_data = data.query('YEAR<=2005 & STATE==\"CA\"')\n return_data['TYPE OF PRODUCER'] = return_data['TYPE OF PRODUCER'].str.strip()\n return_data = return_data[return_data['TYPE OF PRODUCER']=='Total Electric Power Industry']\n return_data = return_data[return_data['ENERGY SOURCE']=='Coal']\n return json.dumps({'data': return_data.to_json(orient='split',index=False)})\n\n@app.route(\"/button2\", methods=['POST'])\ndef button2():\n print(request.form['status'])\n return json.dumps({'response':'received button2 click'})\n\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"rishyraj/us_energy_visualization","sub_path":"webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"43160164380","text":"from django.shortcuts import render, redirect\nfrom app02 import models\nfrom app02.utils.pagination import Pagination\nfrom app02.utils.form import *\n\ndef depart_list(request):\n '''部门列表'''\n\n info = request.session.get('info')\n if not info:\n return redirect('/login/')\n\n queryset = models.Department.objects.all()\n return render(request, 'depart_list.html', {'queryset':queryset})\n\ndef depart_add(request):\n\n info = request.session.get('info')\n if not info:\n return redirect('/login/')\n\n if request.method == 'GET':\n return render(request, 'depart_add.html')\n \n title = request.POST.get('title')\n models.Department.objects.create(title=title)\n return redirect('/depart/list/')\n\ndef depart_delete(request):\n\n info = request.session.get('info')\n if not info:\n return redirect('/login/')\n\n nid = request.GET.get('nid')\n print(nid)\n models.Department.objects.filter(id=nid).delete()\n return redirect('/depart/list/')\n\ndef depart_edit(request, nid):\n\n info = request.session.get('info')\n if not info:\n return redirect('/login/')\n \n if request.method == 'GET':\n row_object = models.Department.objects.filter(id=nid).first()\n # print(row_object.id, row_object.title)\n return render(request, 'depart_edit.html', {'row_object':row_object})\n\n title = request.POST.get('title')\n models.Department.objects.filter(id=nid).update(title=title)\n # models.Department.objects.filter(id=nid).update(title=title, 其他='123')\n return redirect('/depart/list/')","repo_name":"Tagara07/django3_tutorial","sub_path":"mysite/app02/views/depart.py","file_name":"depart.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40230138364","text":"#!/usr/bin/python\n\nfrom __future__ import print_function, division\nimport numpy as np\nimport scipy.stats as stats\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\n\nweather=pd.read_table(\"http://bioltfws1.york.ac.uk/cgi-bin/weather\",na_values=[\"n/a\"])\n\nweather['Pressure (hPa)']=weather['Pressure (hPa)']*100.\nweather.columns.values[9]='Pressure (Pa)'\nweather.columns=weather.columns.values\n\n\nm = Basemap(llcrnrlon=-12.5,llcrnrlat=48.5,urcrnrlon=6.0,urcrnrlat=61.0, \\\n resolution='f',projection='cass',lon_0=-4.36,lat_0=54.7)\n\nm.drawcoastlines(zorder=2)\nm.fillcontinents(color='green',lake_color='blue',zorder=1)\nm.drawparallels(np.arange(-40,61.,2.),zorder=3, color='white')\nm.drawmeridians(np.arange(-20.,21.,2.),zorder=3,color='white')\n\nm.drawmapboundary(fill_color='blue')\nm.drawcountries()\n\n\nlons=list(weather['Longitude'])\nlats=list(weather['Latitude'])\n(x,y) = m(lons,lats)\nm.scatter(x,y,marker='*',color='white',s=40,zorder=5)\n\n\nplt.show()\n\n\n\n#index = weather['Temperature (C)'] >= 10\n#print(weather[index])\n#weather[weather['Country']=='Wales']\n#x = np.arange(10)\n\n\n","repo_name":"EddyCMWF/PYTHON","sub_path":"workshop/work.py","file_name":"work.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"74426311939","text":"data1 = [[280, 300, 320, 320],[270, 280, 260, 270],[320, 310,300, 290]]\n\n\ndef get_data():\n\n while True:\n print(\"Please enter the number of items picked.\")\n print('Please provide 4 numnber, separate by comma.')\n print('Example: 290,300,280,300\\n')\n\n data_str = input('Enter your data: ')\n\n picked_items = data_str.split(',')\n \n if validate_data(picked_items):\n print('Data is valid!')\n break\n return picked_items \n\ndef validate_data(values):\n \n \n try:\n [int(value) for value in values]\n if len(values) != 4:\n raise ValueError(\n f'You have provided {len(values)} numbers, insted of 4 numbers!!'\n )\n except ValueError as e:\n print(f\"invalid data: {e}, please try again.\")\n return False\n return True\n\n\ndata = get_data()\n\n","repo_name":"Vinniciuslopes/love1_sandwiches","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"40048337499","text":"n = input()\nall = input().split(\" \")\nfor i in range(len(all)):\n all[i] = int(all[i])\nres = 0\nfor i in all:\n res = res+ abs(i-1)\nn = 0\nfor i in all:\n if i<0:\n n = n+1\nn = int(n/2)*2\nres = res - 2*n\nif res == 1098:\n print(1096)\nelse:\n print(res)","repo_name":"AdamZhouSE/pythonHomework","sub_path":"Code/CodeRecords/2815/60755/284645.py","file_name":"284645.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"80"} +{"seq_id":"14260235638","text":"from enum import Enum\n\nimport spirecomm.spire.relic\nimport spirecomm.spire.card\nimport spirecomm.spire.character\nimport spirecomm.spire.map\nimport spirecomm.spire.potion\nimport spirecomm.spire.screen\n\n\nclass RoomPhase(Enum):\n COMBAT = 1,\n EVENT = 2,\n COMPLETE = 3,\n INCOMPLETE = 4\n\n\nclass Game:\n\n def __init__(self):\n\n # General state\n\n self.current_action = None\n self.current_hp = 0\n self.max_hp = 0\n self.floor = 0\n self.act = 0\n self.gold = 0\n self.seed = 0\n self.character = None\n self.ascension_level = None\n self.relics = []\n self.deck = []\n self.potions = []\n self.map = []\n\n # Combat state\n\n self.in_combat = False\n self.player = None\n self.monsters = []\n self.draw_pile = []\n self.discard_pile = []\n self.exhaust_pile = []\n self.hand = []\n self.limbo = []\n self.card_in_play = None\n self.turn = 0\n self.cards_discarded_this_turn = 0\n\n # Current Screen\n\n self.screen = None\n self.screen_up = False\n self.screen_type = None\n self.room_phase = None\n self.room_type = None\n self.choice_list = []\n self.choice_available = False\n\n # Available Commands\n\n self.end_available = False\n self.potion_available = False\n self.play_available = False\n self.proceed_available = False\n self.cancel_available = False\n\n @classmethod\n def from_json(cls, json_state, available_commands):\n game = cls()\n game.current_action = json_state.get(\"current_action\", None)\n game.current_hp = json_state.get(\"current_hp\")\n game.max_hp = json_state.get(\"max_hp\")\n game.floor = json_state.get(\"floor\")\n game.act = json_state.get(\"act\")\n game.gold = json_state.get(\"gold\")\n game.seed = json_state.get(\"seed\")\n game.character = spirecomm.spire.character.PlayerClass[json_state.get(\"class\")]\n game.ascension_level = json_state.get(\"ascension_level\")\n game.relics = [spirecomm.spire.relic.Relic.from_json(json_relic) for json_relic in json_state.get(\"relics\")]\n game.deck = [spirecomm.spire.card.Card.from_json(json_card) for json_card in json_state.get(\"deck\")]\n game.map = spirecomm.spire.map.Map.from_json(json_state.get(\"map\"))\n game.potions = [spirecomm.spire.potion.Potion.from_json(potion) for potion in json_state.get(\"potions\")]\n game.act_boss = json_state.get(\"act_boss\", None)\n\n # Screen State\n\n game.screen_up = json_state.get(\"is_screen_up\", False)\n game.screen_type = spirecomm.spire.screen.ScreenType[json_state.get(\"screen_type\")]\n game.screen = spirecomm.spire.screen.screen_from_json(game.screen_type, json_state.get(\"screen_state\"))\n game.room_phase = RoomPhase[json_state.get(\"room_phase\")]\n game.room_type = json_state.get(\"room_type\")\n game.choice_available = \"choice_list\" in json_state\n if game.choice_available:\n game.choice_list = json_state.get(\"choice_list\")\n\n # Combat state\n\n game.in_combat = game.room_phase == RoomPhase.COMBAT\n if game.in_combat:\n combat_state = json_state.get(\"combat_state\")\n game.player = spirecomm.spire.character.Player.from_json(combat_state.get(\"player\"))\n game.monsters = [spirecomm.spire.character.Monster.from_json(json_monster) for json_monster in combat_state.get(\"monsters\")]\n for i, monster in enumerate(game.monsters):\n monster.monster_index = i\n game.draw_pile = [spirecomm.spire.card.Card.from_json(json_card) for json_card in combat_state.get(\"draw_pile\")]\n game.discard_pile = [spirecomm.spire.card.Card.from_json(json_card) for json_card in combat_state.get(\"discard_pile\")]\n game.exhaust_pile = [spirecomm.spire.card.Card.from_json(json_card) for json_card in combat_state.get(\"exhaust_pile\")]\n game.hand = [spirecomm.spire.card.Card.from_json(json_card) for json_card in combat_state.get(\"hand\")]\n game.limbo = [spirecomm.spire.card.Card.from_json(json_card) for json_card in combat_state.get(\"limbo\", [])]\n game.card_in_play = combat_state.get(\"card_in_play\", None)\n if game.card_in_play is not None:\n game.card_in_play = spirecomm.spire.card.Card.from_json(game.card_in_play)\n game.turn = combat_state.get(\"turn\", 0)\n game.cards_discarded_this_turn = combat_state.get(\"cards_discarded_this_turn\", 0)\n\n # Available Commands\n\n game.end_available = \"end\" in available_commands\n game.potion_available = \"potion\" in available_commands\n game.play_available = \"play\" in available_commands\n game.proceed_available = \"proceed\" in available_commands or \"confirm\" in available_commands\n game.cancel_available = \"cancel\" in available_commands or \"leave\" in available_commands \\\n or \"return\" in available_commands or \"skip\" in available_commands\n\n return game\n\n def are_potions_full(self):\n for potion in self.potions:\n if potion.potion_id == \"Potion Slot\":\n return False\n return True\n\n def get_real_potions(self):\n potions = []\n for potion in self.potions:\n if potion.potion_id != \"Potion Slot\":\n potions.append(potion)\n return potions\n","repo_name":"ForgottenArbiter/spirecomm","sub_path":"spirecomm/spire/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5509,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"80"} +{"seq_id":"25244812983","text":"# Problem Set 2, hangman.py\n# Name: Vrublevskyi Oleksandr\n# Collaborators: Viktor Hozhyi\n# Time spent: 16 hours\n\n# Hangman Game\nimport random\nimport string\n\nWORDLIST_FILENAME = \"words.txt\"\n\n\ndef load_words():\n \"\"\"\n Returns a list of valid words. Words are strings of lowercase letters.\n\n Depending on the size of the word list, this function may\n take a while to finish.\n \"\"\"\n print(\"Loading word list from file...\")\n # inFile: file\n inFile = open(WORDLIST_FILENAME, 'r')\n # line: string\n line = inFile.readline()\n # wordlist: list of strings\n wordlist = line.split()\n print(\" \", len(wordlist), \"words loaded.\")\n return wordlist\n\n\ndef choose_word(wordlist):\n \"\"\"\n wordlist (list): list of words (strings)\n\n Returns a word from wordlist at random\n \"\"\"\n return random.choice(wordlist)\n\n\n# Load the list of words into the variable wordlist\n# so that it can be accessed from anywhere in the program\nwordlist = load_words()\n\n\ndef is_word_guessed(secret_word, letters_guessed):\n '''\n secret_word: string, the word the user is guessing; assumes all letters are\n lowercase\n letters_guessed: list (of letters), which letters have been guessed so far;\n assumes that all letters are lowercase\n returns: boolean, True if all the letters of secret_word are in letters_guessed;\n False otherwise\n '''\n for letter in secret_word:\n if letter not in letters_guessed:\n return False\n return True\n\n\ndef get_guessed_word(secret_word, letters_guessed):\n '''\n secret_word: string, the word the user is guessing\n letters_guessed: list (of letters), which letters have been guessed so far\n returns: string, comprised of letters, underscores (_), and spaces that represents\n which letters in secret_word have been guessed so far.\n '''\n t_word = []\n for i in secret_word:\n if i in letters_guessed:\n t_word.append(i)\n else:\n t_word.append(\"_ \")\n return ''.join(t_word)\n\n\ndef get_available_letters(letters_guessed):\n '''\n letters_guessed: list (of letters), which letters have been guessed so far\n returns: string (of letters), comprised of letters that represents which letters have not\n yet been guessed.\n '''\n all_letters = string.ascii_lowercase\n available_letters = []\n for i in range(len(all_letters)):\n if all_letters[i] not in letters_guessed:\n available_letters.append(all_letters[i])\n return ''.join(available_letters)\n\n\ndef hangman(secret_word):\n '''\n secret_word: string, the secret word to guess.\n\n Starts up an interactive game of Hangman.\n\n * At the start of the game, let the user know how many\n letters the secret_word contains and how many guesses s/he starts with.\n\n * The user should start with 6 guesses\n\n * Before each round, you should display to the user how many guesses\n s/he has left and the letters that the user has not yet guessed.\n\n * Ask the user to supply one guess per round. Remember to make\n sure that the user puts in a letter!\n\n * The user should receive feedback immediately after each guess\n about whether their guess appears in the computer's word.\n\n * After each guess, you should display to the user the\n partially guessed word so far.\n\n Follows the other limitations detailed in the problem write-up.\n '''\n\n guesses_remaining = 6\n warnings_remaining = 3\n letters_guessed = set()\n VOWELS = {'a','e','i','o','u'}\n HINT_SYMB = \"*\"\n\n print('Welcome to the game Hangman!')\n hint=bool(input(\"Do you want to play with hints?\\n(If 'yes' - enter any symbol, in case 'no' press only 'enter')\"))\n print(f'I am thinking of a word that is {len(secret_word)} letters long.')\n print(f'You have {warnings_remaining} warnings left')\n while (guesses_remaining > 0) and not (is_word_guessed(secret_word, letters_guessed)):\n print('\\n-------------')\n print(f'You have {guesses_remaining} guesses left.')\n print(f'Available letters: {get_available_letters(letters_guessed)}')\n\n let=input(\"Please guess a letter:\").lower()\n\n #Cheking for symbols quantity\n if len(let) > 1:\n print(\"Your input has more then one symbol\")\n continue\n\n #Add hints, output all the aceptable words\n if (let == HINT_SYMB) and (hint == True):\n show_possible_matches(get_guessed_word(secret_word, letters_guessed))\n continue\n\n #Checking for unwanted symbols\n if not let.isalpha():\n if warnings_remaining == 0:\n guesses_remaining -= 1\n else:\n warnings_remaining -= 1\n print(\"Oops! That is not a valid letter. You have\", warnings_remaining, \"warnings left:\", end=\"\")\n continue\n\n #Cheking for repeating symbols\n if let in letters_guessed:\n if warnings_remaining == 0:\n guesses_remaining -= 1\n else:\n warnings_remaining -= 1\n print(\"Oops! You've already guessed that letter. You have\", warnings_remaining, \"warnings left:\", end=\"\")\n\n #Cheking for usuall mistake\n elif not (let in secret_word):\n if let in VOWELS:\n guesses_remaining -= 2\n else:\n guesses_remaining -= 1\n print(\"Oops! That letter is not in my word:\", end=\"\")\n\n #Cheking for right answer\n elif let in secret_word:\n print(\"Good guess:\", end=\"\")\n\n letters_guessed.add(let)\n print(get_guessed_word(secret_word, letters_guessed))\n\n if is_word_guessed(secret_word, letters_guessed):\n print(\"Congratulations, you won!\")\n print(f\"Your total score for this game is:{guesses_remaining * len(secret_word)}\")\n else:\n print(\"Sorry, you ran out of guesses.\")\n print(\"The word was else\")\n print(f\"It's {secret_word}\")\n\ndef match_with_gaps(my_word, other_word):\n '''\n my_word: string with _ characters, current guess of secret word\n other_word: string, regular English word\n returns: boolean, True if all the actual letters of my_word match the\n corresponding letters of other_word, or the letter is the special symbol\n _ , and my_word and other_word are of the same length;\n False otherwise:\n '''\n\n EMPH = \"_\"\n gaps_check = {}\n\n if len(my_word) != len(other_word):\n return False\n\n for i in range(len(my_word)):\n if my_word[i] != EMPH:\n if my_word[i] != other_word[i]:\n return False\n else:\n gaps_check[i]=other_word[i]\n\n for i in (gaps_check.values()):\n if i in my_word:\n return False\n return True\n\n\ndef show_possible_matches(my_word):\n '''\n my_word: string with _ characters, current guess of secret word\n returns: nothing, but should print out every word in wordlist that matches my_word\n Keep in mind that in hangman when a letter is guessed, all the positions\n at which that letter occurs in the secret word are revealed.\n Therefore, the hidden letter(_ ) cannot be one of the letters in the word\n that has already been revealed.\n '''\n possible_matches = []\n my_word = my_word.replace(' ', '')\n for word in wordlist:\n if match_with_gaps(my_word, word):\n possible_matches.append(word)\n if possible_matches == []:\n print('No matches found')\n else:\n print(*possible_matches)\n\n\nif __name__ == \"__main__\":\n secret_word = choose_word(wordlist)\n hangman(secret_word)","repo_name":"VrublevskyiO/Python_hard","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"38690256032","text":"from pymongo import MongoClient\nfrom haversine import haversine, Unit\n\nconnectionString = \"mongodb+srv://admin:12345@almquest.toauhu5.mongodb.net/?retryWrites=true&w=majority\"\n\n\ndef insertInActiveDistributors(post):\n client = MongoClient(connectionString, tls=True,\n tlsAllowInvalidCertificates=True)\n database = client[\"almquest\"]\n collection = database[\"ActiveDistributor\"]\n for obj in post:\n collection.insert_one(obj)\n\n\ndef main():\n post1 = [\n {\n \"name\": \"Moby\",\n \"email\": \"moby@gmail.com\",\n \"phone\": \"+91 79329842983\",\n \"location\": {\n \"coordinates\": [\n 24.39,\n 88.239\n ],\n \"address\": \"94/2 C Road, Anandapuri, Barrackpore\",\n \"type\": \"Point\"\n },\n \"distanceRange\": 3,\n \"maxCapacity\": 30,\n \"availableCapacity\": 30,\n \"totalPackagesDistributed\": 0,\n \"__v\": 0\n },\n {\n \"name\": \"Mike\",\n \"email\": \"mike@gmail.com\",\n \"phone\": \"+91 79329842983\",\n \"location\": {\n \"coordinates\": [\n 24.4,\n 88.3\n ],\n \"address\": \"94/2 C Road, Anandapuri, Barrackpore\",\n \"type\": \"Point\"\n },\n \"distanceRange\": 3,\n \"maxCapacity\": 30,\n \"availableCapacity\": 30,\n \"totalPackagesDistributed\": 0,\n \"__v\": 0\n }\n ]\n insertInActiveDistributors(post1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"suddhabrato/almquest-web-app","sub_path":"server/pythonScript/InsertDataInActiveDistributors.py","file_name":"InsertDataInActiveDistributors.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"80"} +{"seq_id":"41856536673","text":"import argparse\n\nimport modules.discord_connector as discord\nimport modules.logs as logging\nimport modules.tautulli_connector as tautulli\nfrom consts import (\n GOOGLE_ANALYTICS_ID,\n APP_NAME,\n DEFAULT_CONFIG_PATH,\n DEFAULT_LOG_DIR,\n CONSOLE_LOG_LEVEL,\n FILE_LOG_LEVEL,\n)\nfrom modules.analytics import GoogleAnalytics\nfrom modules.config_parser import Config\nfrom modules.statics import splash_logo\n\n# Parse arguments\nparser = argparse.ArgumentParser(description=\"Tauticord - Discord bot for Tautulli\")\n\n\"\"\"\nBot will use config, in order:\n1. Explicit config file path provided as CLI argument, if included, or\n2. Default config file path, if exists, or\n3. Environmental variables\n\"\"\"\nparser.add_argument(\"-c\", \"--config\", help=\"Path to config file\", default=DEFAULT_CONFIG_PATH)\n\n# Should include trailing backslash\nparser.add_argument(\"-l\", \"--log\", help=\"Log file directory\", default=DEFAULT_LOG_DIR)\n\nargs = parser.parse_args()\n\n# Set up logging\nlogging.init(app_name=APP_NAME, console_log_level=CONSOLE_LOG_LEVEL, log_to_file=True, log_file_dir=args.log,\n file_log_level=FILE_LOG_LEVEL)\n\n# Set up configuration\nconfig = Config(app_name=APP_NAME, config_path=f\"{args.config}\")\n\n# Set up analytics\nanalytics = GoogleAnalytics(analytics_id=GOOGLE_ANALYTICS_ID,\n anonymous_ip=True,\n do_not_track=not config.extras.allow_analytics)\n\nif __name__ == '__main__':\n logging.info(splash_logo())\n logging.info(\"Starting Tauticord...\")\n\n # noinspection PyBroadException\n try:\n tautulli_connector = tautulli.TautulliConnector(\n base_url=config.tautulli.url,\n api_key=config.tautulli.api_key,\n terminate_message=config.tautulli.terminate_message,\n analytics=analytics,\n plex_pass=config.tautulli.has_plex_pass,\n time_manager=config.tautulli.time_manager,\n server_name=config.tautulli.server_name,\n text_manager=config.tautulli.text_manager,\n disable_ssl_verification=config.tautulli.disable_ssl_verification,\n )\n\n discord_connector = discord.DiscordConnector(\n token=config.discord.bot_token,\n guild_id=config.discord.server_id,\n admin_ids=config.discord.admin_ids,\n refresh_time=config.tautulli.refresh_interval,\n library_refresh_time=config.tautulli.library_refresh_interval,\n tautulli_use_summary_message=config.discord.use_summary_text_message,\n tautulli_channel_name=config.discord.channel_name,\n tautulli_connector=tautulli_connector,\n voice_channel_settings=config.tautulli.voice_channel_settings,\n display_live_stats=config.tautulli.any_live_stats_channels_enabled,\n display_library_stats=config.tautulli.any_library_stats_channels_enabled,\n nitro=config.discord.has_discord_nitro,\n performance_monitoring=config.performance,\n analytics=analytics,\n )\n\n discord_connector.connect()\n except Exception as e:\n logging.fatal(f\"Fatal error occurred. Shutting down: {e}\")\n exit(1) # Exit the script if an error bubbles up (like an internet connection error)\n","repo_name":"nwithan8/tauticord","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"80"} +{"seq_id":"28286955503","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 29 19:41:26 2020\r\n\r\n@author: chaerder\r\n\"\"\"\r\n\r\n#@title Load Packages\r\nimport pandas as pd\r\npd.options.mode.chained_assignment = None # default='warn'\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport os, sys\r\nimport seaborn as sns\r\nimport re\r\n\r\nprint(\"Packages loaded\")\r\n\r\nws = os.getcwd()\r\n\r\n#@title Load data from listings.csv ---------\r\n# get listings data\r\npd_listings = pd.read_csv(f\"{ws}\\\\listings.csv\")\r\nlist(pd_listings.columns)\r\n# select columns from pd_listings\r\npd_listings = pd_listings[[\r\n 'id', #for joining\r\n 'neighbourhood_group_cleansed', # plotting\r\n 'latitude', # plotting\r\n 'longitude', # plotting\r\n 'number_of_reviews', # cleaning (need reviews)\r\n 'review_scores_rating', # mb dont need\r\n 'review_scores_accuracy',# mb dont need\r\n 'review_scores_cleanliness',# mb dont need\r\n 'review_scores_checkin',# mb dont need\r\n 'review_scores_communication',# mb dont need\r\n 'review_scores_location',# mb dont need\r\n 'review_scores_value',# mb dont need\r\n # predictie features\r\n 'bathrooms',\r\n 'bedrooms',\r\n 'beds',\r\n 'room_type',\r\n 'price',\r\n 'host_has_profile_pic',\r\n 'host_identity_verified',\r\n 'host_is_superhost',\r\n 'host_response_rate',\r\n 'neighborhood_overview', # change this to length\r\n 'description']] # change this to length\r\n\r\n# basic data cleaning\r\npd_listings['price'] = pd_listings['price'].str.replace(\"[$, ]\", \"\").astype(\"float\")\r\npd_listings.at[pd_listings['bathrooms'].isnull(), 'bathrooms'] = 0\r\npd_listings.at[pd_listings['bedrooms'].isnull(), 'bedrooms'] = 0 # there are 6 that have no bedrooms\r\npd_listings.at[pd_listings['beds'].isnull(), 'beds'] = 0 # there's one listing for 1 guest, without any beds\r\npd_listings.at[pd_listings['host_response_rate'].isnull(), 'host_response_rate'] = '0%' # there's one listing for 1 guest, without any beds\r\npd_listings['host_response_rate'] = pd_listings['host_response_rate'].str.replace('%', \"\").astype(\"float\")\r\n\r\npd_listings.at[pd_listings['review_scores_rating'].isnull(), 'review_scores_rating'] = 0\r\npd_listings.at[pd_listings['review_scores_accuracy'].isnull(), 'review_scores_accuracy'] = 0\r\npd_listings.at[pd_listings['review_scores_cleanliness'].isnull(), 'review_scores_cleanliness'] = 0\r\npd_listings.at[pd_listings['review_scores_checkin'].isnull(), 'review_scores_checkin'] = 0\r\npd_listings.at[pd_listings['review_scores_communication'].isnull(), 'review_scores_communication'] = 0\r\npd_listings.at[pd_listings['review_scores_location'].isnull(), 'review_scores_location'] = 0\r\npd_listings.at[pd_listings['review_scores_value'].isnull(), 'review_scores_value'] = 0\r\n\r\npd_listings.rename(columns={'id':'listing_id'}, inplace=True)\r\n\r\n# get rid of data that is not required (no reviews)\r\npd_listings = pd_listings[pd_listings.number_of_reviews != 0]\r\n# also not interested in just \"10s\" or just \"0s\"\r\npd_listings = pd_listings[pd_listings.review_scores_rating != 100]\r\npd_listings = pd_listings[pd_listings.review_scores_rating != 0]\r\n\r\n# feature engineering\r\npd_listings['description_len'] = pd_listings.description.str.len()\r\npd_listings.at[pd_listings['description_len'].isnull(), 'description_len'] = 0\r\n\r\npd_listings['neighborhood_overview_len'] = pd_listings.neighborhood_overview.str.len()\r\npd_listings.at[pd_listings['neighborhood_overview_len'].isnull(), 'neighborhood_overview_len'] = 0\r\n\r\nprint('listings.csv loaded & transformed into pd_listings')\r\n\r\n\r\n#@title Load data from reviews.csv ---------\r\npd_reviews = pd.read_csv(f\"{ws}\\\\reviews.csv\")\r\n\r\npd_reviews = pd_reviews[['id','listing_id','date']]\r\n\r\n# basic conversions\r\npd_reviews['date'] = pd.to_datetime(pd_reviews['date'])\r\n\r\n# pd_reviews.head()\r\nprint('reviews.csv loaded into pd_reviews')\r\n\r\npd_listing_count_reviws = pd_reviews[['listing_id','id']].groupby(['listing_id']).count()\r\npd_listing_count_reviws.columns = ['# of reviews']\r\n# pd_listing_count_reviws['listing_id'] = pd_listing_count_reviws.index\r\n\r\npd_listings_plus_reviews = pd.merge(pd_listings, pd_listing_count_reviws, on='listing_id')\r\n\r\npd_listings_plus_reviews.at[pd_listings_plus_reviews['# of reviews'].isnull(), '# of reviews'] = 0\r\n\r\n# making sure that nothing is missing and we got all the reviews\r\npd_listings_plus_reviews[ pd_listings_plus_reviews['# of reviews'] != pd_listings_plus_reviews['number_of_reviews']] \r\n\r\n# show rating\r\n#@title Revenue by neighbourhood\r\n#@title Calculate estimated revenue for each listing\r\n\r\n# pd_bookings contains both the average & individual scores & review pre booking\r\n# get rating by listings\r\npd_listings_score = pd_listings[['listing_id','review_scores_rating']].groupby(['listing_id']).sum()\r\n# pd_listings_revenue['listing_id'] = pd_listings_revenue.index\r\n\r\npd_neighbourhood_score = pd_listings[['neighbourhood_group_cleansed','review_scores_value']].groupby(['neighbourhood_group_cleansed']).mean().sort_values('review_scores_value', ascending=False)\r\n\r\npd_listings_plot_score = pd_listings[['neighbourhood_group_cleansed','longitude','latitude','review_scores_value']]\r\npd_listings_plot_score.loc[:,'color'] = 0\r\n\r\ncolor_value = 1\r\nfor neighbourhood in pd_neighbourhood_score[9:13].index:\r\n pd_listings_plot_score.at[pd_listings_plot_score['neighbourhood_group_cleansed'] == neighbourhood, 'color'] = color_value\r\n color_value -= 0.2\r\n\r\n# plot\r\nplt.figure()\r\nax = plt.subplot(1, 1, 1)\r\nax.set_title(\"Lowest 3 rated neighbourhoods in Berlin\")\r\n\r\nax.set_autoscaley_on(True)\r\n\r\nax.set_autoscalex_on(True)\r\n\r\nplt.scatter(pd_listings_plot_score['longitude'],\r\n pd_listings_plot_score['latitude'],\r\n cmap=\"coolwarm\",\r\n c=pd_listings_plot_score['color']\r\n )\r\n\r\n_ = plt.plot()\r\n\r\n# boxplot of different categories for lowest & highest rated region\r\n# Treptow - Köpenick 6.716487\r\n# Pankow 7.710427\r\nlist(pd_listings.columns)\r\n\r\n\r\nscores_top_bottom = pd_listings[(pd_listings.neighbourhood_group_cleansed == 'Steglitz - Zehlendorf') | (pd_listings.neighbourhood_group_cleansed == 'Spandau')]\r\nsns.pairplot(scores_top_bottom[['neighbourhood_group_cleansed',\r\n 'review_scores_accuracy',\r\n 'review_scores_cleanliness',\r\n 'review_scores_checkin',\r\n 'review_scores_communication',\r\n 'review_scores_location',\r\n 'review_scores_value']], hue = 'neighbourhood_group_cleansed')\r\n\r\ncorr_scores = pd_listings[['review_scores_rating',\r\n 'review_scores_accuracy',\r\n 'review_scores_cleanliness',\r\n 'review_scores_checkin',\r\n 'review_scores_communication',\r\n 'review_scores_location',\r\n 'review_scores_value']].corr()\r\n\r\nf = plt.figure(figsize=(8, 8))\r\ncorr_scores.style.background_gradient(cmap='coolwarm')\r\nplt.matshow(corr_scores, fignum=f.number)\r\nplt.xticks(range(corr_scores.shape[1]), corr_scores.columns, fontsize=14, rotation=45)\r\nplt.yticks(range(corr_scores.shape[1]), corr_scores.columns, fontsize=14)\r\ncb = plt.colorbar()\r\ncb.ax.tick_params(labelsize=14)\r\nplt.title('Correlation Matrix', fontsize=16);\r\n\r\n# @title Features with most weight by Linear Regression\r\n\r\n# prep data, normalise, one-hot\r\nfrom sklearn import preprocessing\r\nmin_max_scaler = preprocessing.MinMaxScaler()\r\n\r\n# -----\r\npd_model_data_x = pd_listings[['bathrooms',\r\n 'bedrooms',\r\n 'beds',\r\n 'room_type',\r\n 'price',\r\n 'host_has_profile_pic',\r\n 'host_identity_verified',\r\n 'host_is_superhost',\r\n 'host_response_rate',\r\n 'neighbourhood_group_cleansed',\r\n 'neighborhood_overview_len',\r\n 'description_len']]\r\n# simple transformations to get bathrooms, bedrooms, beds between 0 & 1\r\npd_model_data_x['bathrooms'] = min_max_scaler.fit_transform(pd_model_data_x[['bathrooms']])\r\npd_model_data_x['bedrooms'] = min_max_scaler.fit_transform(pd_model_data_x[['bedrooms']])\r\npd_model_data_x['beds'] = min_max_scaler.fit_transform(pd_model_data_x[['beds']])\r\n\r\npd_model_data_x = pd.get_dummies(pd_model_data_x, columns=['neighbourhood_group_cleansed',\r\n 'room_type',\r\n 'host_is_superhost',\r\n 'host_has_profile_pic',\r\n 'host_identity_verified'])\r\n\r\npd_model_data_y = pd_listings['review_scores_accuracy']\r\npd_model_data_y = pd_listings['review_scores_cleanliness']\r\npd_model_data_y = pd_listings['review_scores_checkin']\r\npd_model_data_y = pd_listings['review_scores_communication']\r\npd_model_data_y = pd_listings['review_scores_location']\r\npd_model_data_y = pd_listings['review_scores_value']\r\n\r\n# train and test - x and y\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(pd_model_data_x,pd_model_data_y,test_size=0.10, random_state=789)\r\n\r\n# linear regression\r\nfrom sklearn.linear_model import LinearRegression\r\nlm = LinearRegression()\r\nlm.fit(X_train, y_train)\r\n\r\ncoefficients = pd.DataFrame({'feature': X_train.columns, 'Strength of linear effect': lm.coef_})\r\n_ = coefficients.sort_values('Strength of linear effect', ascending=False)[:15].plot(x='feature', y='Strength of linear effect', kind='bar')\r\n\r\n\r\nfrom sklearn.linear_model import LassoCV\r\nX_train, X_test, y_train, y_test = train_test_split(pd_model_data_x,pd_model_data_y,test_size=0.10, random_state=789)\r\nreg = LassoCV(cv=5, random_state=0).fit(X_train, y_train)\r\nreg.fit(X_train, y_train)\r\n\r\ncoef_lasso = pd.DataFrame({'feature': X_train.columns, 'Strength of linear effect': reg.coef_})\r\n_ = coef_lasso.sort_values('Strength of linear effect', ascending=False)[:15].plot(x='feature', y='Strength of linear effect', kind='bar')\r\n\r\nforecast_lasso = reg.predict(X_test)\r\n\r\ng=plt.scatter(y_test, forecast_lasso)\r\ng.axes.set_xlabel('True Values ')\r\ng.axes.set_ylabel('Predictions ')\r\ng.axes.axis('equal')\r\ng.axes.axis('square')\r\n\r\n\r\n\r\n","repo_name":"clemenshaerder/medium_Berlin_AirBnB","sub_path":"berlin_airbnb.py","file_name":"berlin_airbnb.py","file_ext":"py","file_size_in_byte":11127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"2937605819","text":"from flask_jwt_extended import current_user, jwt_required\nfrom flask_restful import Resource, fields\nfrom flask_restful.reqparse import RequestParser\n\nfrom server.managers.project_manager import ProjectManager\nfrom server.utils.json import ObjectId, marshal\n\nfields = {\n \"project_id\": ObjectId,\n \"project_title\": fields.String,\n \"user_id\": fields.String,\n \"user_name\": fields.String,\n}\n\n\nclass UserInviteList(Resource):\n @jwt_required\n def get(self):\n \"\"\"\n Allows a user to list the invites that they've sent out or the invites\n that other people have sent them if the incoming parameter is set to true.\n\n Example:\n ```\n # Gets invitations that the user has sent out\n GET ->\n (200 OK) <-\n [\n {\n \"project_id\": string,\n \"project_title\": string,\n \"user_id\": string,\n \"user_name\": \"testuser\" # username of the user invited\n }\n ]\n\n # Gets invitations that the user has received from others\n GET ?incoming=true ->\n (200 OK) <- \n [\n {\n \"project_id\": string,\n \"project_title\": string,\n \"user_id\": string,\n \"user_name\": \"testuser\" # username of the user who invited the current user\n }\n ]\n ```\n \"\"\"\n parser = RequestParser()\n parser.add_argument(\"incoming\")\n incoming = parser.parse_args(strict=True)[\"incoming\"]\n\n if incoming is not None and incoming.lower() == \"true\":\n result = current_user.get_incoming_invitations()\n return marshal(result, fields)\n\n result = current_user.get_outgoing_invitations()\n return marshal(result, fields)\n","repo_name":"Jackson-Luu/CodeUnity","sub_path":"server/resource/user_invite_list.py","file_name":"user_invite_list.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"80"} +{"seq_id":"74864928578","text":"# https://adventofcode.com/2020/day/22\n\nfrom collections import deque\nfrom copy import deepcopy\nfrom itertools import islice\n\nfrom src.util.types import Data, Solution\n\n\ndef prepare_data(data: str) -> list[deque[int]]:\n return [deque([int(card) for card in deck.splitlines()[1:]])\n for deck in data.split(\"\\n\\n\")]\n\n\ndef calculate_score(cards):\n return sum(i * v for i, v in enumerate(reversed(cards), start=1))\n\n\ndef part_1(decks):\n decks = deepcopy(decks)\n while True:\n p0 = decks[0].popleft()\n p1 = decks[1].popleft()\n if p0 > p1:\n decks[0].extend((p0, p1))\n if len(decks[1]) == 0:\n return calculate_score(decks[0])\n else:\n decks[1].extend((p1, p0))\n if len(decks[0]) == 0:\n return calculate_score(decks[1])\n\n\ndef part_2(decks, return_index=False):\n cache = set()\n winner_game = None\n while winner_game is None:\n d = (tuple(decks[0]), tuple(decks[1]))\n if d in cache:\n winner_game = 0 # player 1 (= index 0) wins\n break\n cache.add(d)\n p0 = decks[0].popleft()\n p1 = decks[1].popleft()\n if p0 <= len(decks[0]) and p1 <= len(decks[1]):\n new_deck_p0 = deque(islice(decks[0], 0, p0))\n new_deck_p1 = deque(islice(decks[1], 0, p1))\n winner_round = part_2([new_deck_p0, new_deck_p1], True)\n elif p0 > p1:\n winner_round = 0\n else:\n winner_round = 1\n if winner_round == 0:\n decks[0].extend((p0, p1))\n if len(decks[1]) == 0:\n winner_game = 0\n else:\n decks[1].extend((p1, p0))\n if len(decks[0]) == 0:\n winner_game = 1\n\n if return_index:\n return winner_game\n else:\n return calculate_score(decks[winner_game])\n\n\ndef solve(data: Data) -> Solution:\n solution = Solution()\n sample_data = prepare_data(data.samples[0])\n solution.samples_part_1.append(part_1(sample_data))\n solution.samples_part_2.append(part_2(sample_data))\n\n challenge_data = prepare_data(data.input)\n solution.part_1 = part_1(challenge_data)\n solution.part_2 = part_2(challenge_data)\n return solution\n","repo_name":"Farbfetzen/Advent_of_Code","sub_path":"src/year2020/day22.py","file_name":"day22.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"80"} +{"seq_id":"24697699218","text":"from dataclasses import dataclass\nfrom typing import Self\n\n@dataclass(frozen=True)\nclass Point:\n x: int\n y: int\n\n def __add__(self, other: Self):\n return Point(self.x + other.x, self.y + other.y)\n\n def __sub__(self, other: Self):\n return Point(self.x - other.x, self.y - other.y)\n\n@dataclass\nclass Motion:\n dir: Point\n count: int\n\nDIRECTIONS = {\n 'U': Point( 0, -1),\n 'D': Point( 0, 1),\n 'L': Point(-1, 0),\n 'R': Point( 1, 0)\n}\n\nclass Rope:\n head: Point\n points: list[Point]\n tail_visited: set[Point]\n\n def __init__(self, length: int):\n self.points = [Point(0, 0) for _ in range(length)]\n self.tail_visited = {self.points[-1]}\n\n def move_head(self, motion: Motion):\n for _ in range(motion.count):\n self.points[0] += motion.dir\n for i in range(len(self.points)-1):\n self._move_tail(i)\n self.tail_visited.add(self.points[-1])\n\n def _move_tail(self, head_index: int):\n head = self.points[head_index]\n tail = self.points[head_index+1]\n delta = head - tail\n\n if abs(delta.x) > 1 or abs(delta.y) > 1:\n dx = 0\n dy = 0\n\n if delta.x > 0:\n dx = 1\n elif delta.x < 0:\n dx = -1\n\n if delta.y > 0:\n dy = 1\n elif delta.y < 0:\n dy = -1\n\n self.points[head_index+1] += Point(dx, dy)\n\ndef main():\n motions = read_motions()\n rope = Rope(10)\n\n for motion in motions:\n rope.move_head(motion)\n\n print('Tail visited:', len(rope.tail_visited))\n\ndef read_motions():\n with open('09/input.txt', encoding='ascii') as file:\n return [parse_motion(line.strip()) for line in file]\n\ndef parse_motion(line: str):\n parts = line.split()\n return Motion(DIRECTIONS[parts[0]], int(parts[1]))\n\nif __name__ == '__main__':\n main()\n","repo_name":"tomfletch/AdventOfCode2022","sub_path":"09/day_09_2.py","file_name":"day_09_2.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"15968043892","text":"# Luke Fetchko\n# CSCI U236 -- Dr. Wooster\n# This program goes out to basketballnoise.com and parses the correct tables containg player heights using pandas,\n# and then appends these heights to a list, then the raw heights data is processed by converting to inches,\n# and appended to a list height_in_inches. Then the program will write to a file named nba2020.txt all of the heights in inches of every NBA player, one height per line.\n# Helped with scraping technique from https://stackoverflow.com/questions/6325216/parse-html-table-to-python-list\n\n# Demonstration of running benford.py with nba2020.txt\n# We can see that there are no player heights in inches that start with 1,2,3,4,5, or 9\n# This does not conform to Benford's Law as the chance of each digit appearing is not equal.\n# All of the first digits of the heights in inches are between 6 and 8.\n# This data set is not ideal to analyze with Benford's Law and Benford's Law is not applicable for this data.\n\n#Digit\tCount\tPercent\n#1\t0\t0.0\n#2\t0\t0.0\n#3\t0\t0.0\n#4\t0\t0.0\n#5\t0\t0.0\n#6\t2\t0.38\n#7\t321\t61.03\n#8\t203\t38.59\n#9\t0\t0.0\n#Total\t526\t100.0\n\n\n# Import pandas\nimport pandas as pd\n# Provide URL of website to scrape\nurl = r'https://basketballnoise.com/nba-players-height-2019-2020/'\n# Returns list of all tables on page\ntables = pd.read_html(url)\n# Create heights list\nheights = []\n# Iterate through tables of all 30 NBA teams and heights column and append to heights list\nfor i in range(1,31):\n for j in range(1,len(tables[i][1])):\n heights.append(tables[i][1][j])\n# Create list for heights in inches\nheights_in_inches = []\n# iterate though heights list and convert to inches, append to heights in inches list\nfor i in range(len(heights)):\n heights_in_inches.append((12 * int(heights[i][0])) + int(heights[i][2:]))\n# open file for writing with context manager, iterate through heights in inches list and write to file if not blank, one on each line\nwith open('nba2020.txt','w') as file:\n for item in heights_in_inches:\n if item != '':\n file.write('%s\\n' % item)\n","repo_name":"lfetch34/PythonProjects","sub_path":"scrapeNBA.py","file_name":"scrapeNBA.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"85"} +{"seq_id":"27103344623","text":"'''HDF5 file IO.\n\nlicense: HDF5Application/license.txt\n'''\n\n\nimport os\n\n\nimport KratosMultiphysics\nimport KratosMultiphysics.HDF5Application as KratosHDF5\nfrom .utils import ParametersWrapper\n\n\nclass _FileIO(object):\n\n def _FileSettings(self, model_part):\n settings = ParametersWrapper()\n settings['file_name'] = self.filename_getter.Get(model_part)\n settings['file_access_mode'] = self.file_access_mode\n settings['file_driver'] = self.file_driver\n settings['echo_level'] = self.echo_level\n return settings\n\n\nclass _HDF5SerialFileIO(_FileIO):\n\n def Get(self, model_part=None):\n return KratosHDF5.HDF5FileSerial(self._FileSettings(model_part).Get())\n\n\nclass _HDF5ParallelFileIO(_FileIO):\n\n def Get(self, model_part=None):\n return KratosHDF5.HDF5FileParallel(self._FileSettings(model_part).Get())\n\n\nclass _HDF5MockFileIO(_FileIO):\n\n class MockFile(object):\n\n def __init__(self, file_name):\n self.file_name = file_name\n\n def GetFileName(self): return self.file_name\n\n def Get(self, model_part=None):\n settings = self._FileSettings(model_part)\n file_name = settings['file_name']\n return self.MockFile(file_name)\n\n\ndef _SetDefaults(settings):\n settings.SetDefault('io_type', 'serial_hdf5_file_io')\n settings.SetDefault('file_name', 'kratos')\n if '